Access指令元素

时间:2016-05-24 15:40:10

标签: angular angular2-directives

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

1 个答案:

答案 0 :(得分:2)

应避免访问ElementRef.nativeElement...。使用ElementRefElementRef.nativeElement使用Renderer中的方法就可以了。

对于预定义样式,您不需要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';
}
相关问题