当前位置:网站首页>ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.

2022-06-23 13:25:00 51CTO

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.

 

Solution :

  • Asynchronous update ( It is recommended to use )
  • Force change detection , But it will trigger the change detection of sub components , This causes the parent component properties to change again

Parent.Component.ts

      
      
@Component({
selector:"app-parent"
})

export class ParentComponent implements OnInit,AfterViewInit {
public text = " Information for subcomponents ";


constructor(private cdr: ChangeDetectorRef){}

ngOnInit(){}

// The disadvantages of this method : When there are many sub components , Not easy to control . Not recommended
ngAfterViewInit(){
this.cdr.detectChanges();
}
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.

Child.Component.ts

      
      
@Component({
selector:"app-child"
})

export class ChildComponent implements OnInit, AfterViewInit {
@Input text;

constructor(private parentComponent: ParentComponent){}

ngOnInit(){}

ngAfterViewInit() {
// Two methods of asynchronous update

// The first one is
setTimeout( ()=>{
this.parentComponent.text="update message"
},2000);

// The second kind
Promise.resolve(null).then( ()=> {this.parentComponent.text="update message"});

}
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.

 

 


 

【 Copyright notice 】 The copyright of this blog belongs to the author , For any form of reprint, please contact the author for authorization and indicate the source !

【 Important note 】 This article is my study record , Arguments and opinions only represent individuals and do not represent the truth of technology at that time , The goal is to learn from yourself and be fortunate enough to be an experience that can be shared with others , Therefore, mistakes will be accepted and corrected with an open mind , But it doesn't mean that the blog is correct at the moment !

【Gitee Address 】 Qin Haocheng :​ ​https://gitee.com/wjw1014​


原网站

版权声明
本文为[51CTO]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206231232079897.html