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'的屬性或方法。 –