版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/friend_ship/article/details/81773057
ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous vlalue:"给子组件的信息".Current value:"update message".
解决方案:
- 异步更新
- 强制进行变更检测,但是会触发子组件的变更检测,再次导致父组件属性改变
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"});
}
}