问题描述
我的组件具有取决于当前日期时间的样式.在我的组件中,我有以下功能.
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%)'
我知道只有在检查值时才会在开发模式下出现异常.如果检查值与更新值不同,则抛出异常.
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();
}
...但没有成功.
推荐答案
在更改后显式运行更改检测:
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“检查后表达式已更改"组件属性取决于当前日期时间时的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!