function gets called several times

青春壹個敷衍的年華 提交于 2019-11-26 14:39:39

问题


I want to display a dataList. Some values are calculate from a function. It seems angular2 calls the calculate function many times.

  <tr *ngFor="let data of dataList">
    <td>{{ data.no }}</td>
    <td>{{ data.name }}</td>
    <td>{{ calculateFunction(data.price) }}</td>
  </tr>

Console will output "calculate..." many times, more than dataList.length.

calculateFunction() {
  console.log('calculate...');
  return ...;
}

Should I worry about that for performance or just let angular2 do this?


回答1:


The caculateFunction(data.price) function will be called every time Angular runs change detection for the component (more precisely for the embedded view created by ngFor). This is because updating DOM is part of change detection and Angular needs to call caculateFunction to know what value to use for DOM update. And change detection cycle can run quite often. So if you have 3 items in the list and CD is triggered 3 times initially, you will see that the function is called 9 times.

If you inspect the updateRenderer function, you shoul see something along these lines:

function(_ck,_v) {
    var _co = _v.component;
    var currVal_0 = _co.calculateFunction(_v.context.$implicit);
    _ck(_v,3,0,currVal_0);
  }

Read more about how Angular updates DOM in The mechanics of DOM updates in Angular.

Should I worry about that for performance or just let angular2 do this?

If calculateFunction(data.price) returns the same result for the same price, it's better to calculate these values beforehand for each item and simply renderer them in the template.

<td>{{ data.no }}</td>
<td>{{ data.name }}</td>
<td>{{ data.calculatePrice) }}</t

In this way you will avoid performance decreasing function calls.




回答2:


you can change the components changeDetectionStrategy to onPush. after that, your calculateFunction function does not call several times.

to do that :

in your component:

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css'],
 changeDetection: ChangeDetectionStrategy.OnPush // this line
})

export class AppComponent {

  ....

  calculateFunction(value) {
    console.log('calculate...');
    return ...;
  }
}

and in your app.component.html :

 <tr *ngFor="let data of dataList">
  <td>{{ data.no }}</td>
  <td>{{ data.name }}</td>
  <td>{{ calculateFunction(data.price) }}</td>
 </tr>


来源:https://stackoverflow.com/questions/45207357/function-gets-called-several-times

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