Angular *ngFor calling method multiple times problem

Background:
When using *ngFor directive try to avoid using methods inside the *ngFor loop.
When methods are used inside the *ngFor template databinding Angular triggers the method on every possible change detection. Angular does this because a method has side effects, its “impure”. Angular don’t know if the return value of the method has changed, and triggers a change detection check as often as possible.

Result:
If you set a console.log() inside your method that is called from within a *ngFor loop and tries to trigger some sort of change detection interaction (e.g. component init, click or mouse scroll depending on component implementation). You will see that the method is being triggered many more times than expected.

Example problem:
(heroes.component.html)

<ul class="heroes">
  <li *ngFor="let hero of heroes"
    [class.selected]="hero === selectedHero"
    (click)="onSelect(hero)">
    <h5>{{getHeroName(hero)}}</h5>
  </li>
</ul>

(heroes.component.ts)

getHeroName(hero: Hero) {
  console.log(hero.name);
  return hero.name;
}

The console.log will log 21 times on init and another 20 times for every “click”. The expected result is 10 console.logs upon init.

Above example could be fixed by instead calling the name property on the iterated variable (hero):

<ul class="heroes">
  <li *ngFor="let hero of heroes"
    [class.selected]="hero === selectedHero"
    (click)="onSelect(hero)">
    <h5>{{hero.name}}</h5>
  </li>
</ul>

Solution:
Use a property inside the *ngFor directive instead, so prepare a collection with correct data and save to properties instead of using methods. So the template will iterate over an already “prepared” model collection.

If call on method inside the *ngFor directive is hard to avoid, at least make sure the code is fast and is performant since it will be called many, many times in a row.

Source: https://www.reddit.com/r/Angular2/comments/59532r/function_being_called_multiple_times/

Leave a Reply