2016-05-24 79 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'的属性或方法。 –