ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked on ng 4
This seems to keep going on and on even though all of the answers and advice has already been posted above.
1.The right way to fix this is to re-architect/restructure your components and data handling to work with a single change detection pass from the top down. This means that no child component may change a value that is used in the template of a parent component. Re-evaluate what you have built and verify that the data flows only in one direction, down the component tree. This may be as simple as moving your code out of ngAfterViewInit and into ngOnInit in some cases.
2.this.changeDetectorRef.detectChanges(); is the official and recognized way for handling this in the less than 5% of cases where the first step is problematic.
1.Be very careful when doing anything in ngAfterViewInit as changing values that are used in the DOM can cause this error.
2.Be very careful when using any of the Check or Checked lifecycle hooks as they may be called on every change detection cycle.
3.setTimeout can work around this, but the two solutions above are preferred.
4.Ignoring this error in dev mode and being happy that production mode “fixes” the error is not valid as explained above. These checks are not made in prod mode, but your prod mode code is still leaving changes undetected and causing the view and data to be out of sync. This can be harmless in some cases, but can lead to data/view corruption and worse problems if ignored.
5.One way data flow hasn’t really changed a lot in Angular, so posting that you hit this in version X of Angular isn’t too helpful.
6.Adding more lifecycle hooks or states is not a solution to this. Developers would just add code that violates one way data flow into those hooks and trigger this same error.
Finally, just remember that this error is not indicating a problem with Angular. This error is here to let you know that you have done something wrong in your code and that you are violating the one way data flow system that makes Angular fast and efficient.
The posts above and many blog posts go more deeply into this and are worth reading as you should understand this one way data flow model and how to build components and pass data within it.