Angular 指令的问题

Issue with Angular directive

在模块中,我已经声明了指令,但是 <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>

@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;
    }
}

我会这样做:

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

Plunker Example

别忘了导入 HostBinding:

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