I wonder how does Angular's *ngFor
directive actually work under the hood? I would like to know the whole process that happens when I use the directive.
For downvoters: I've seen the ng-for-of file, although there is no single usage of passed to *ngFor
array's e.g. join()
method that I know is invoked. Thanks for your support :)
Here is the plunker that shows the behavior: https://plnkr.co/edit/IXVxWrSOhLBgvSal6PWL?p=preview
Here is a high level overview. Suppose you define your template like this:
Then it's transformed to the following by the compiler:
Then Angular applies
ngForOf
directive to the template element. Since this directive's host element is template, it injects thetemplateRef
. It also injects theviewContainerRef
that acts as an anchor element and will be used to add DOM elements alongside:The directive defines
ngForOf
as an input and then waits until it's initialized and creates a differ:Then on each check detection cycle it compares the values to the previous values using this differ:
If the values changed, it applies the changes doing the the following things:
1) generates embedded view context for each item in
items
2) creates embedded view with this context using the
templateRef
which effectively renders new value in the DOM3) adds relevant values to context
Now, your question:
It's called by the function
normalizeDebugBindingValue
here because your application is running in the development mode:If you enable production mode this function no longer be called, check the plunker.