2017-01-05 111 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 –