我的组件具有依赖于当前日期时间的样式。在我的组件中,我有如下函数。
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从当前datetime开始计算。如果dtoDate在过去24小时内,则颜色会发生变化。
准确的错误如下:
表达式在检查后发生了变化。先前值:'hsl(123, 80%, 49%)'。当前值:'hsl(123, 80%, 48%)'
我知道异常只出现在开发模式的值被检查的时刻。如果检查值与更新值不同,则抛出异常。
因此,我尝试在以下钩子方法中更新每个生命周期的当前datetime,以防止异常:
ngAfterViewChecked()
{
console.log( "! changement de la date du composant !" );
this.dateNow = new Date();
}
...但是没有成功。
在我们的例子中,我们通过在组件中添加changeDetection来FIXED,并调用ngAfterContentChecked中的detectChanges(),代码如下所示
@Component({
selector: 'app-spinner',
templateUrl: './spinner.component.html',
styleUrls: ['./spinner.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class SpinnerComponent implements OnInit, OnDestroy, AfterContentChecked {
show = false;
private subscription: Subscription;
constructor(private spinnerService: SpinnerService, private changeDedectionRef: ChangeDetectorRef) { }
ngOnInit() {
this.subscription = this.spinnerService.spinnerState
.subscribe((state: SpinnerState) => {
this.show = state.show;
});
}
ngAfterContentChecked(): void {
this.changeDedectionRef.detectChanges();
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}