【问题标题】:Access directive element访问指令元素
【发布时间】:2016-05-24 15:40:10
【问题描述】:

如何在指令类本身中访问我的指令附加到的元素?我需要对元素的引用才能通过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');
    }
}

【问题讨论】:

    标签: angular angular2-directives


    【解决方案1】:

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

    【讨论】:

    • Renderer 方法要求将nativeElement 作为参数传递(从一些更高的 beta 版本开始),这仍然可以。您应该避免直接在代码中访问nativeElement 的属性或方法。
    猜你喜欢
    • 2013-05-22
    • 1970-01-01
    • 2016-06-17
    • 2013-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-15
    相关资源
    最近更新 更多