Angular 角度2指令更改检测,指令未更新

Angular 角度2指令更改检测,指令未更新,angular,Angular,我有一个显示数字的Angular 2应用程序。数字可以是负数或正数。如果该值为负,我将字体颜色设置为红色。我是通过指令来做这件事的。该数字通过发射器不断更新 我遇到的问题是当值从负值变为正值时。指令没有接收到此更改,运行速度非常慢,即颜色没有更新。我必须点击屏幕上的任何地方,然后字体颜色就会改变。 我不认为在我需要的时候会发生变化检测 如何在基础值更新的同时更新此指令 我的指令是这样的 import { Directive, ElementRef, Input } from '@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';
    }
}
<td negativeValueStyle>{{data.return | number: '1.2-2'}}%</td>
import{Directive,ElementRef,Input}来自'@angular/core';
@指令({选择器:'[negativeValueStyle]'})
导出类NegativeValueStyleDirective{
构造函数(私有el:ElementRef){}
ngAfterContentChecked(){
if(this.el.nativeElement.innerHTML<0)
this.el.nativeElement.style.color='red';
其他的
this.el.nativeElement.style.color='black';
}
}
它被应用到UI中,如下所示

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';
    }
}
<td negativeValueStyle>{{data.return | number: '1.2-2'}}%</td>
{{data.return}编号:'1.2-2'}}

哦,天哪,使用angular及其功能似乎是一种错误的方法。我认为更好的方法是将
style.color
上的绑定与通过
negativeValueStyle
指令传递的值结合使用:

未测试的预发代码

@指令({选择器:'[negativeValueStyle]})
导出类NegativeValueStyleDirective{
@输入('negativeValueStyle')
公共价值:数字;
@主机绑定('style.color')
公共获取颜色():字符串{
返回此值。值<0?'red':'black';
}
@主机绑定('innerHtml')
public get innerHtml():字符串{
返回此值。值+'%';
}
}
然后,您可以像这样使用此指令:

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

哦,天哪,使用angular及其功能似乎是一种错误的方法。我认为更好的方法是将
style.color
上的绑定与通过
negativeValueStyle
指令传递的值结合使用:

未测试的预发代码

@指令({选择器:'[negativeValueStyle]})
导出类NegativeValueStyleDirective{
@输入('negativeValueStyle')
公共价值:数字;
@主机绑定('style.color')
公共获取颜色():字符串{
返回此值。值<0?'red':'black';
}
@主机绑定('innerHtml')
public get innerHtml():字符串{
返回此值。值+'%';
}
}
然后,您可以像这样使用此指令:

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


谢谢,这是一种很好的做事方式。我复制了Ng2网站设置css样式的例子,但我更喜欢这个。谢谢,这是一种很好的做事方式。我复制了Ng2网站设置css样式的例子,但我更喜欢这个。