ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.
解决方案:
- 异步更新(建议使用)
- 强制进行变更检测,但是会触发子组件的变更检测,再次导致父组件属性改变
Parent.Component.ts
@Component({
selector:"app-parent"
}) export class ParentComponent implements OnInit,AfterViewInit {
public text = "给子组件的信息"; constructor(private cdr: ChangeDetectorRef){} ngOnInit(){} // 该方法缺点: 子组件多的情况下,不易控制。不建议使用
ngAfterViewInit(){
this.cdr.detectChanges();
}
}
Child.Component.ts
@Component({
selector:"app-child"
}) export class ChildComponent implements OnInit, AfterViewInit {
@Input text; constructor(private parentComponent: ParentComponent){} ngOnInit(){} ngAfterViewInit() {
// 异步更新两种方式 // 第一种
setTimeout( ()=>{
this.parentComponent.text="update message"
},2000); // 第二种
Promise.resolve(null).then( ()=> {this.parentComponent.text="update message"}); }
}
参考原文:https://blog.csdn.net/friend_ship/article/details/81773057