简体   繁体   English

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

[英]How to cache a value in an ngFor directive in Angular2?

My component has the activity property which has the totalLoad() method that computes extensive numbers, but could also return null if parameters are wrong ( otherwise return a structure containing 'load'). 我的组件具有activity属性,该属性具有计算大量数字的totalLoad()方法,但如果参数错误,也可以返回null(否则返回包含'load'的结构)。 In an ngFor, I'd like to access to load properties if and only if the method doesn't return null. 在ngFor中,当且仅当方法不返回null时,我才想访问加载属性。 How would you do that? 你会怎么做?

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

I assumed from your question that you are trying to avoid template errors when trying to access some property, right? 我从您的问题中假设您在尝试访问某些属性时试图避免模板错误,对吧?

If I'm right, you can do it using the Safe Navigation Operator : 如果我是对的,你可以使用Safe Navigation Operator

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

Check a simple demo using the operator: 使用运算符检查一个简单的演示:

PLUNKER PLUNKER

Binding to a method this way in the view is usually a bad idea. 在视图中以这种方式绑定到方法通常是个坏主意。 Every time Angular runs change detection, this method is executed. 每次Angular运行更改检测时,都会执行此方法。

A better approach is to store the calculated values in an array and use ngFor on this array. 更好的方法是将计算值存储在数组中,并在此数组上使用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>

I finally did this (it's the union of the two answers above): 我终于这样做了(这是上面两个答案的结合):

In the component.ts: 在component.ts中:

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

In the component.html: 在component.html中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM