Stéphane de Luca
Stéphane de Luca

Reputation: 13611

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'). In an ngFor, I'd like to access to load properties if and only if the method doesn't return null. How would you do that?

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

Upvotes: 1

Views: 897

Answers (3)

developer033
developer033

Reputation: 24894

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:

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

Check a simple demo using the operator:

PLUNKER

Upvotes: 2

St&#233;phane de Luca
St&#233;phane de Luca

Reputation: 13611

I finally did this (it's the union of the two answers above):

In the component.ts:

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

In the component.html:

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

Upvotes: 0

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658225

Binding to a method this way in the view is usually a bad idea. Every time Angular runs change detection, this method is executed.

A better approach is to store the calculated values in an array and use ngFor on this array.

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>

Upvotes: 1

Related Questions