doorman
doorman

Reputation: 16949

ngFor using index to indentify items

I have the following ngFor were images are being displayed. If an image is missing (Http 404) I simply want to hide the img element. The problem is that the imgMissing variable is global for all the elements. We could easily solve this with logic in the component file or by specifying a separate component file for the item part.

But is it possible to solve this only within the template e.g. by using the index to identify the missing image item?

<div *ngFor="let item of items; let i = index">
    <img *ngIf="!imgMissing" [src]="item.imgSrc" (error)="imgMissing=true;" />
</div>

Upvotes: 1

Views: 426

Answers (1)

Dan Wilson
Dan Wilson

Reputation: 4047

Just use the native onerror handler to set the style.

<div *ngFor="let item of items; let i = index">
    <img [src]="item.imgSrc" onerror="this.style.display='none'" />
</div>

Upvotes: 3

Related Questions