Angular 6 ngFor

3

You can explain why the ngFor directive is triggering the "TriggerTest" function twice, and the array called "items" it is only traversing has stored only one element of the object type.

app.component.html

<h1>TESTANDO NGFOR</h1>
<div *ngFor="let item of items">
  <div>{{gatilhoTeste(item)}}</div>
</div>

app.component.ts

import { Component, enableProdMode } from '@angular/core';

enableProdMode();
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  items: any[] = [{id:'String Elemento'}]

  gatilhoTeste(item){
    console.log(item);
  }
}

    
asked by anonymous 29.08.2018 / 23:17

1 answer

2

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.logitprintsseveral  times?

Well,thebrowserconsolelifecycleiscompletelydifferentfromthelifecycleofanAngularcomponent.Bothareseparate,oneistheresponsibilityofthebrowseritself,anotheroftheapplication.Whenacomponentchangedetectionoccurs,thebrowserdoesnotknowthis,itonlyprintswhatitreceives.

Therefore,sincethecomponentisreloadedmultipletimesduringthisprocess,theconsole.logisconsequentlycalledseveraltimes.

XProductionDevelopment

Thereisanotherpointthatis,whenrunindevelopmentmode,thechangedetectioncycleoccurstwiceforeachcomponent.Inproductionmode,thiscycleiscalledonlyonce.

Ifyoubuildyour project in production , it will only print once.

link

Stackblitz: link

    
30.08.2018 / 17:29