如何简化模板中同一个函数的调用次数?

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

getCell 函数 return 是一个具有三个属性(textwidthheight)的对象。

我可以在模板中声明一个变量来接收 getCell return 值,然后用它来减少 calls.Because 的 return 值的函数数量 getCell相同参数功能相同

伪代码:

<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>

这还不是最大的问题。

这里的问题是在视图中调用值返回表达式,是 angular 中的性能问题。

Angular 没有办法检测视图是否在没有 运行 在后台启用该表达式的情况下发生变化。

这意味着每个变化检测周期angular都会运行这些函数。

想象一下,如果在 mouseMove 事件或 hover 或类似事件上触发 changeDetection。

根据函数实际执行的操作,这会给应用程序带来巨大的负载,使它的运行速度变得非常慢。

您可以使用 ngLet.

执行您要求的操作
<ui-td *ngLet = "getCell(item.key,index) as cell"
     [text]="cell.text"
     [width]="cell.width"
     [height]="cell.height">
</ui-td>

你也可以使用*ngIf

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

但我会尝试找到一种无需调用函数即可完成相同操作的方法,这绝对是个麻烦,尤其是在 *ngFor

内部