簡體   English   中英

如何在Angular2中的ngFor指令中緩存一個值?

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

我的組件具有activity屬性,該屬性具有計算大量數字的totalLoad()方法,但如果參數錯誤,也可以返回null(否則返回包含'load'的結構)。 在ngFor中,當且僅當方法不返回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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM