The cause of this "problem" is the change detection
angular.
This process aims, in a brief explanation, to catch all its componentes
and render them in visão
.
Each time a detection cycle is called, the component in question is completely reloaded, updating both the view
as to the model
.
This is a standard behavior, necessary for components to maintain a state always up-to-date.
In your scenario, this seems problematic as it appears to have more than one item in the array. However, this is not the case.
If we make a div
to show all the content, it presents only one:
<h1>TESTANDO NGFOR</h1>
<div *ngFor="let item of items">
<div>{{item.id}}</div>
</div>
Prints only one widget.
Yeah, but why when I do console.log
he prints several
times?
Well, the lifecycle of the browser console is completely different from the lifecycle of an Angular component. Both are separate, one is the responsibility of the browser itself, the other of the application. When a component change detection occurs, the browser does not know it, it only prints what it receives.
Therefore, as the component is recharged several times during this process, the console.log
is consequently called several times.
Development X Production
There is another point that is, when run in development mode, the change detection cycle occurs twice for each component.
Already in production mode, this cycle is called only once.
If you build your project in production mode, it will only print once.
https://angular.io/guide/lifecycle-hooks
Stackblitz: https://stackblitz.com/edit/angular-ts7s7a
You have cleared the cache of
console
?– Marconi
Yeah, I tried other browsers and the same thing happens. If I remove from within the array the object type element and insert a string type element it only runs correctly, only once.
– Cleriston Martins Cardoso
How many
*ngFor
are within the component?– Marconi
This is the only ngFor of the component, actually I left it so I can reset all the possibilities of loop.. I’m beginning to believe that it might be either an Angular bug or a natural Angular behavior..
– Cleriston Martins Cardoso
Please post the code instead of image
– Eduardo Vargas
printing the name variable what it shows?
– Lucas Brogni
@Lucas Brongni, it shows the object inside the array twice.
– Cleriston Martins Cardoso
@eduardovargas changed the code to make it simpler
– Cleriston Martins Cardoso
I believe he prints for each time the DOM changes so he prints once and then one after inserting the ngFOR element
– Eduardo Vargas