【发布时间】:2016-05-24 15:40:10
【问题描述】:
如何在指令类本身中访问我的指令附加到的元素?我需要对元素的引用才能通过Renderer 服务应用样式。使用ElementRef.nativeElement 有效,但那是officially discouraged,所以我想知道我们还有什么其他选择。
import {Directive, ElementRef, Renderer} from 'angular2/core';
@Directive({
selector: '[autoGrow]',
host: {
'(focus)': 'onFocus()',
'(blur)': 'onBlur()'
}
})
export class AutoGrowDirective {
constructor(private _el: ElementRef, private _renderer: Renderer) {}
/*
* This code works, but uses ElementRef.nativeElement to reference the element
*/
onFocus() {
this._renderer.setElementStyle(this._el.nativeElement, 'width', '200px');
}
onBlur() {
this._renderer.setElementStyle(this._el.nativeElement, 'width', '120px');
}
}
【问题讨论】:
标签: angular angular2-directives