Reputation: 693
I have the follow design:
Parent
+ Child 1
+ Child 2
Child 2 contains and input field, the user hits ENTER and it emits an event. Child 1 intercepts it and emits an execute event which is intercepted by the Parent. The Parent executes a search and sends the results back to Child 1 via an Input().
In one scenario when the user navigates to the Parent with a reload=Y flag the search is run automatically based on the previously saved criteria. I do this in ngOnInit by checking the route params reload=Y and then emitting the same execute event, it goes to the parent and the results come back via Input(), this is working however I also get this error in the console -
ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: '[object Object]'.
I followed this article: https://blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error-e3fd9ce7dbb4
and used a setTimeout() as described and now the error is gone. What exactly happened here?
What exactly is setTimeout doing. The official explanation is "The setTimeout function schedules a "macrotask" which will be executed in the following VM turn".
So setTimetout delays the execution of the defined function until the next change detection cycle? What is meant by "next VM turn"?
Upvotes: 0
Views: 371
Reputation: 3243
By using the SetTimeout you’re basically branching part of your flow into a new change detection cycle. The one that will happen after completing the task.
The error you are seeing is basically a defence mechanism from Angular to prevent multiple sources updating the same property several times in the same change detection cycle. If this was allowed it would be really tricky to figure out the final value displayed and who produced it.
That’s the reason you no longer see the error, because the multiple changes will no longer be done on the same change detection cycle. You are taking ownership of splitting them into different timings so Angular is fine with that
Upvotes: 3