如何在 Angular2 的 ngFor 指令中缓存一个值?

How to cache a value in an ngFor directive in Angular2?

我的组件有 activity 属性,它有计算大量数字的 totalLoad() 方法,但如果参数错误(否则 return 包含 'load') 的结构。 在 ngFor 中,当且仅当方法不为 return null 时,我想访问加载属性。 你会怎么做?

<td *ngFor="let d of monthDays">
    {{activity.totalLoad(member.code, d.day).load}} h
</td>

根据你的问题,我假设你在尝试访问一些 属性 时试图避免模板错误,对吗?

如果我是对的,你可以使用 Safe Navigation Operator:

<td *ngFor="let d of monthDays">
    {{activity.totalLoad(member.code, d.day)?.load}} h
</td>

检查一个使用运算符的简单演示:

PLUNKER

在视图中以这种方式绑定到方法通常不是一个好主意。 每次 Angular 运行变更检测时,都会执行此方法。

更好的方法是将计算值存储在一个数组中,然后在该数组上使用 ngFor

ngOnInit() {
  this.totalLoads = this.monthDays
  .map(md => this.activity.totalLoad(this.member.code, md.day).load);
}
<td *ngFor="let td of totalLoads">
    {{td}} h
</td>

我终于做到了(这是上面两个答案的结合):

在component.ts中:

ngOnInit() {
  this.totalLoads = this.monthDays
  .map(md => this.activity.totalLoad(this.member.code, md.day).load);
}

在component.html中:

<td *ngFor="let td of totalLoads">
    {{td ? td+" h":""}}
</td>