I am just playing with Angular change detection cycle and I found something that I can't understand.
We have following component's view:
<!-- ver:1 call() was called 3 times -->
<div>
<p>call(); {{ call() }}</p>
Name obtained from the API: <b>{{ data.name }}</b>
</div>
<!-- ver:2 call() was called just once -->
<div>
Name obtained from the API: <b>{{ data.name }}</b>
<p>call(); {{ call() }}</p>
</div>
So in the ver:1 call() is executed 3 times, we have such order: 1.call() method, 2.render name from the API.
In the ver:2 call() is executed just once and we have such order: 1.render name from the API, 2.call() method.
I think the 'effect' comes from the forked version of the zone.js in the Angular, but I didn't find anything that can explain such behavior in the Angular repo.
There is an error in the line
<b>{{ data.name }}</b>
becausedata
is undefined.The 2nd version line
<p>call(); {{ call() }}</p>
is not executed till thedata
is available, whendata
gets assigned there are no errors so all the lines in the template get rendered. So it is called only once.The 1st ver is called multiple times because
<p>call(); {{ call() }}</p>
is above the error line and gets executed every time there is a change in thedata
variable or there is a template error.The 1st time the method is called on rendering the template for the 1st time and it encounters an error at the above line.
The 2nd time, change detection runs when the error occurs in the template (not sure why change detection runs an extra time when there is a template error).
The 3rd time is when the API response is available,
data
is available, and the complete template is rendered again without any errors.