Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

*ngFor running an infinite loop in angular2

I am trying to render object properties using keys in angular2 using below code:

<ul>
    <li *ngFor="let element of componentModel | keys;let i=index">
      {{element.key}}--{{element.value}}  // 1---Bhushan...loaded only once
      <span  *ngIf="element">{{ loadProperty(i,element) }}</span>
    </li>
</ul>

But I am facing a problem here. The output in the browser in loaded only once. but the method call i.e. loadProperty(i,element) is running in an infinite loop.

loadProperty(i:number,element:any){       
    console.log(element.key+'========'+element.value);
    console.log(element);      
}

means on browser output

(1---Bhushan)

is displayed only once but on the console its running infinitely like below:

Snapshot of the console

I want to call this method only once per iteration.

any inputs?

like image 335
Bhushan Gadekar Avatar asked Jun 17 '16 08:06

Bhushan Gadekar


1 Answers

This is just Angular2 change detection at work calling loadProperty(i,element) over and over in each change detection cycle.

Calling methods from the template is discouraged because they are called very often. You should instead store the result in a property and bind to this property instead.

like image 78
Günter Zöchbauer Avatar answered Nov 16 '22 14:11

Günter Zöchbauer