修复 “Expression has changed after it was checked. Previous value: 'ngIf: true'. Current value: 'ngIf: false'.”#
报错内容#
Expression has changed after it was checked. Previous value: 'ngIf: true'. Current value: 'ngIf: false'.
概述#
虽然这个报错几乎不会影响正常使用,但是看着 Console 中有报错就很难受(
所以想解决这个问题。
开始解决#
-
首先通过这个报错我们大概可以知道,是由于在 Angular 检查值的时候,发现了原有的值与新的值不一致导致的
-
既然 Angular 不能自己去更新,只好我们去帮他更新了,代码如下:
import { AfterContentChecked } from '@angular/core';
// ... 其他代码
@Component({
selector: 'app-test',
templateUrl: './test.component.html'
})
export class TestComponent implements AfterContentChecked {
// ... 其他代码
public constructor(
private titleService: Title,
public layout: LayoutService,
// 更新检查器
private cdr: ChangeDetectorRef,
) {
// ... 其他代码
}
// 检查之后,我们再触发一次更新检查
ngAfterContentChecked(): void {
this.cdr.detectChanges();
}
}
- 这样,我们这个问题就解决了