user15163984
user15163984

Reputation: 534

How to simplify the number of calls to the same function in a template?

<th *ngFor="let item of list;let index = index">
  <ui-td [text]="getCell(item.key,index).text"
         [width]="getCell(item.key,index).width"
         [height]="getCell(item.key,index).height">
  </ui-td>
</th>ruhe1

The getCell function returns an object with three properties(text,width,height).

Can I declare a variable in the template to receive getCell return value and then use it to reduce the number of function calls.Because the return value of getCell function is the same for the same parameter.

Pseudo code:

<th *ngFor="let item of list;let index = index">
  <!-- Pseudo code -->
  <ui-td let obj = getCell(item.key,index)
         [text]="obj.text"
         [width]="obj.width"
         [height]="obj.height">
  </ui-td>
</th>

Upvotes: 0

Views: 42

Answers (1)

tony
tony

Reputation: 945

That's not even the biggest issue here.

The problem here is that calling value returning expression in view, is a performance issue in angular.

Angular has no way to detect if view has changed without running that expression in the background.

This means that each change Detection cycle angular will run these functions.

Imagine if changeDetection is fired on mouseMove event or hover or something like that.

depending on what the function actually does, this can generate huge load on app, slowing it down like hell.

You can do what you are asking for using ngLet.

<ui-td *ngLet = "getCell(item.key,index) as cell"
     [text]="cell.text"
     [width]="cell.width"
     [height]="cell.height">
</ui-td>

you can also use *ngIf

<ui-td *ngIf = "getCell(item.key,index) as cell"
     [text]="cell.text"
     [width]="cell.width"
     [height]="cell.height">
</ui-td>

But i would try to find a way to do the same without calling a function, this is definitely a trouble, especially inside *ngFor

Upvotes: 1

Related Questions