The cause of this "problem" is change detection
of Angular.
This process aims, in a brief explanation, to get all its componentes
and render it in visão
.
Each time a detection cycle is called, the component in question is completely reloaded, updating both view
and model
.
This is a default behavior, which is required for components to maintain an always up-to-date state.
In your scenario, this seems to be problematic as it appears that you have more than one item in the array. But this is not the case.
If we make a div
to show all content, it has only one:
<h1>TESTANDO NGFOR</h1>
<div *ngFor="let item of items">
<div>{{item.id}}</div>
</div>
Printsonlyoneelement.
Okay,butwhywhenIdowithconsole.log
itprintsseveral times?
Well,thebrowserconsolelifecycleiscompletelydifferentfromthelifecycleofanAngularcomponent.Bothareseparate,oneistheresponsibilityofthebrowseritself,anotheroftheapplication.Whenacomponentchangedetectionoccurs,thebrowserdoesnotknowthis,itonlyprintswhatitreceives.
Therefore,sincethecomponentisreloadedmultipletimesduringthisprocess,theconsole.log
isconsequentlycalledseveraltimes.
XProductionDevelopment
Thereisanotherpointthatis,whenrunindevelopmentmode,thechangedetectioncycleoccurstwiceforeachcomponent.Inproductionmode,thiscycleiscalledonlyonce.
Ifyoubuildyour project in production , it will only print once.
link
Stackblitz: link