Search code examples
angularlifecycle

Data flow in Angular lifecycle hook


I was looking at the official documentation of Angular Lifecycle Hook. What makes me confused is the following explanation:

Angular's unidirectional data flow rule forbids updates to the view after it has been composed ...... postpones the log update for one turn of the browser's JavaScript cycle and that's just long enough.

Forbidding updates because the page is already rendered sounds reasonable, but why postponing the update for a tick could solve the problem? Isn't that the view is still composed after a tick?

Please explain to me like I am 5.


Solution

  • Every time en event occurs (like for example when the the delay of a setTimeout has elapsed, and its callback function is executed), Angular starts a change detection and applies the necessary changes to the DOM accordingly.

    What is forbidden is not to update the state of components, and thus the view, when an event occurs. What is forbidden is to update the state of components and thus their view while the change detection is still being done, after they hve been checked already.

    For example, if you try to modify the state of the parent component in the ngAfterViewChecked hook of a child component, you'll get an error from Angular because that's forbidden: Angular has just detected changes on the parent and the child, and you're making changes in the parent, synchronously, during that change detection. Calling setTimeout(), on the other hand, schedules a change for later, and that change will be detected again, and start a new change detection.