dudewad
dudewad

Reputation: 13933

Angular 2: Duplicate Async Calls in Template Loop

I have a template with an ngFor that receives data via an async observable:

<div *ngFor="let result of data.results">
  <div>
    <img [src]="parseSrc(result.src)" alt="{{ getCaption(result.id) | async }}" />
    {{ getCaption(result.id) | async }}
  </div>
</div>

The getCaption method, as you can see, is called twice. The code for it is below:

public getCaption(id: string) {
  return this.data$.results
    .map(results => {
      let result = results.find(r => r.id === id);
      return result && result.caption || '';
    })
}

Is calling it twice an okay way to do this? I feel like calling the function twice is redundant and memory-intensive. What are the other options? I was thinking something like creating a variable in the template would be good, but that's not a facility angular allows. Since this is an ngFor as a result of another async call, performing this logic in the controller code is less than desirable and I feel like there should be a relatively elegant way to perform these two identical calls in the template.

Note: this is a contrived example.

Upvotes: 0

Views: 442

Answers (1)

Teddy Sterne
Teddy Sterne

Reputation: 14221

You can wrap it in an ngIf and use the as syntax to bind it to a local value like so:

<div *ngIf="getCaption(result.id) | async as caption">
    <img [src]="parseSrc(result.src)" alt="{{ caption }}" />
    {{ caption }}
</div>

Upvotes: 2

Related Questions