2017-08-18 50 views
1

在该模块中,我已经宣布了指令,但<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> 

回答

2

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