角度 2 指令更改检测,指令不更新

  • 本文关键字:指令 更新 角度 angular
  • 更新时间 :
  • 英文 :


我有一个显示数字的 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>

,亲爱的,这看起来像是使用Angular及其功能的错误方法。我认为更好的方法是将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>

最新更新