访问指令元素

Access directive element

如何在指令 class 本身内部访问我的指令附加到的元素?我需要引用元素以通过 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');
    }
}

应避免访问 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';
}