【问题标题】:Issue with Angular directiveAngular 指令的问题
【发布时间】:2018-01-27 11:16:16
【问题描述】:

在模块中,我已经声明了指令,但 <div> 没有突出显示。

test.directive.ts

import { Directive, ElementRef, HostListener, Input  } from "@angular/core";

@Directive({
    selector: '[test]'
})
export class TestDirective {
    @Input() highlightColor:string;
    constructor(private el : ElementRef){
        this.el.nativeElement.style.backgroundColor = this.highlightColor;
    }
}

test.template.html

<div test highlightColor="red">directive testing</div>

【问题讨论】:

    标签: angular angular2-directives


    【解决方案1】:

    @Input() highlightColor:string; 在构造函数中的更改检测之前不可用。使用ngOnChanges生命周期钩子。

    export class TestDirective {
        @Input() highlightColor:string;
        constructor(private el : ElementRef){ }
    
        ngOnChanges() {
             this.el.nativeElement.style.backgroundColor = this.highlightColor;
        }
    }
    

    或者如果你知道输入总是一个字符串,你可以在构造函数中使用@Attribute而不使用@Input,如下所示:

    export class TestDirective {
        constructor(private el : ElementRef, @Attribute('highlightColor') color){
            this.el.nativeElement.style.backgroundColor = color;
        }
    }
    

    【讨论】:

      【解决方案2】:

      我会这样做:

      @HostBinding('style.backgroundColor') @Input() highlightColor:string;
      

      Plunker Example

      别忘了导入HostBinding

      import { HostBinding } from '@angular/core';
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-31
        • 2016-07-31
        • 1970-01-01
        • 2014-04-28
        相关资源
        最近更新 更多