0

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.

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.