2
如何访问指令附加到指令类本身内的元素?我需要引用元素以通过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');
}
}
'Renderer'方法需要'nativeElement'作为参数传递(因为稍后的beta版本),这仍然很好。你应该避免**直接在代码中访问'nativeElement'的属性或方法。 –