2017-01-05 112 views
1

我有一個顯示數字的Angular 2應用程序。這個數字可以是負數也可以是正數。如果該值爲負數,我將字體顏色設置爲紅色。我通過一個指令來做這件事。這個數字通過發射器不斷更新。Angular 2指令更改檢測,指令不更新

我遇到的問題是當值從負值變爲正值時。該指令沒有采取這種變化,運行速度很慢,即顏色沒有更新。我必須點擊屏幕上的任何地方,然後字體顏色纔會變化。 當我需要時,我不認爲變化檢測正在發生。

我該如何在底層值的同時更新此指令?

我的指令看起來像這樣...

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

@Directive({ selector: '[negativeValueStyle]' }) 
export class NegativeValueStyleDirective { 

    constructor(private el: ElementRef) { } 

    ngAfterContentChecked() { 

     if (this.el.nativeElement.innerHTML < 0) 
      this.el.nativeElement.style.color = 'red'; 
     else 
      this.el.nativeElement.style.color = 'black'; 
    } 
} 

它被應用到這樣的UI ......

<td negativeValueStyle>{{data.return | number: '1.2-2'}}%</td> 

回答

6

哦,親愛的,看起來像一個錯誤的方法使用角它的能力。我相信,一個更好的方法是結合使用結合上style.color與通過negativeValueStyle指令傳遞的值:提前

未經測試的代碼

@Directive({ selector: '[negativeValueStyle]' }) 
export class NegativeValueStyleDirective { 

    @Input('negativeValueStyle') 
    public value: number; 

    @HostBinding('style.color') 
    public get color(): string { 
     return this.value < 0 ? 'red' : 'black'; 
    } 

    @HostBinding('innerHtml') 
    public get innerHtml(): string { 
     return this.value + '%'; 
    } 
} 

然後你可以使用這個指令像這樣:

<td [negativeValueStyle]="data.return | number: '1.2-2'"></td> 
+0

謝謝,這是一個很好的做事方式。我在複製Ng2網站上設置CSS風格的例子,但我更喜歡這個。 https://angular.io/docs/ts/latest/guide/attribute-directives.html#!#write-directive –