1

I am having a similar code and error as Expression ___ has changed after it was checked where I am changing a variable value in ngAfterViewInit().

One of the answers https://stackoverflow.com/a/35243106/1460595 suggests to manually trigger change detection by calling detectChanges() method of ChangeDetectorRef, which works.

But why do we have to handle change manually when Angular 2 should be handling the change?
Is there some relationship between lifecycle hooks and change detection?

Community
  • 1
  • 1
Flake
  • 1,386
  • 17
  • 31

1 Answers1

0

The problem is caused by a 2nd change detection run after each regular one done by Angular in development mode, to check if the model has stabilized, otherwise this is an indication for a probable bug.

In your case the problem is, that the lifecycle callback ngAfterViewInit is called by the first change detection run. If it updates the modelm the 2nd change detection run throws. With a manual change detection run after the update, Angular gets its remembered values updates and the 2nd CD run won't notify a change.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567