2016-05-24 78 views
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'); 
    } 
} 

回答

2

應該避免使用ElementRef.nativeElement...。使用ElementRefElementRef.nativeElementRenderer的方法就好了。

對於預定義的樣式,您不需要ElementRef。您可以使用主機綁定,如

@Directive({ 
    selector: '[autoGrow]', 
    host: { 
     '(focus)': 'onFocus()', 
     '(blur)': 'onBlur()', 
     '[style.background-color]': '"red"', 
     '[style.left.px]': '"10"', 
     '[style.top.%]': 'someProp', 
    } 
}) 
export class AutoGrowDirective { 
    someProp:number = 20; 

    // or like 
    @HostBinding('style.color') 
    someProp:string = 'grey'; 
} 
+1

'Renderer'方法需要'nativeElement'作爲參數傳遞(因爲稍後的beta版本),這仍然很好。你應該避免**直接在代碼中訪問'nativeElement'的屬性或方法。 –