如何管理Angular2“在检查之后,表达已经改变".组件属性取决于当前日期时间时发生异常 [英] How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime
问题描述
我的组件的样式取决于当前日期时间.在我的组件中,我具有以下功能.
My component has styles that depend on current datetime. In my component I've got the following function.
private fontColor( dto : Dto ) : string {
// date d'exécution du dto
let dtoDate : Date = new Date( dto.LastExecution );
(...)
let color = "hsl( " + hue + ", 80%, " + (maxLigness - lightnessAmp) + "%)";
return color;
}
lightnessAmp
是根据当前日期时间计算得出的.如果dtoDate
在最近24小时内,则颜色会改变.
lightnessAmp
is calculated from the current datetime. The color changes if dtoDate
is in the last 24 hours.
确切的错误如下:
表达已被检查后更改.先前值:"hsl(123,80%,49%)".当前值:"hsl(123,80%,48%)'
Expression has changed after it was checked. Previous value: 'hsl( 123, 80%, 49%)'. Current value: 'hsl( 123, 80%, 48%)'
我知道只有在检查值时,异常才会出现在开发模式中.如果检查的值与更新的值不同,则会引发异常.
I know the exception appear in development mode only at the moment the value is checked. If the checked value is different of the updated value, the exception is thrown.
因此,我尝试使用以下钩子方法在每个生命周期中更新当前日期时间,以防止发生异常:
So I tried to update the current datetime at each lifecycle in the following hook method to prevent the exception:
ngAfterViewChecked()
{
console.log( "! changement de la date du composant !" );
this.dateNow = new Date();
}
...但是没有成功.
...but without success.
推荐答案
在更改后显式运行更改检测:
Run change detection explicitly after the change:
import { ChangeDetectorRef } from '@angular/core';
constructor(private cdRef:ChangeDetectorRef) {}
ngAfterViewChecked()
{
console.log( "! changement de la date du composant !" );
this.dateNow = new Date();
this.cdRef.detectChanges();
}
这篇关于如何管理Angular2“在检查之后,表达已经改变".组件属性取决于当前日期时间时发生异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!