Reputation: 301
I am learning Angular 5 while going through the component interaction part I came across this part
// Redefine `seconds()` to get from the `CountdownTimerComponent.seconds` ...
// but wait a tick first to avoid one-time devMode
// unidirectional-data-flow-violation error
setTimeout(() => this.seconds = () => this.timerComponent.seconds, 0);
I went through the document and also online I tried to find there is no clear explanation given on this topic. Can some one please explain
Upvotes: 4
Views: 2113
Reputation: 1
There is a complete explanation in 2019 Angular guide (angular.io):
Then Angular calls the ngAfterViewInit lifecycle hook at which time it is too late to update the parent view's display of the countdown seconds. Angular's unidirectional data flow rule prevents updating the parent view's in the same cycle. The app has to wait one turn before it can display the seconds. Use setTimeout() to wait one tick and then revise the seconds() method so that it takes future values from the timer component.
Upvotes: 0
Reputation: 657937
1) A tick
is just adding a task (execution of a function) into the browsers event queue, for delayed (async) execution instead of executing it synchronously.
2) To allow the browser to execute pending tasks in the event queue before executing the new code.
3) Some async execution updates the model, Angular recognizes that an async execution is completed and runs change detection. Change detection itself causes the model to change (for example a property or function used in view bindings is modifying the model). The model is only allowed to be modified during some async execution, but not during change detection.
4) By adding the code execution to the browsers event queue instead of executing it immediately, it allows to complete change detection and then the model is updated only in an async execution when the browser executes the task we put in the queue using setTimeout
5) ChangeDetectorRef.detectChanges()
after the model was updated enforces another change detection turn which usually prevents the error.
Upvotes: 5