*ngFor running an infinite loop in angular2

戏子无情 提交于 2019-11-26 03:15:58

问题


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:

I want to call this method only once per iteration.

any inputs?


回答1:


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.



来源:https://stackoverflow.com/questions/37876533/ngfor-running-an-infinite-loop-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!