1

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>
2
  • 1
    What defined whether or not the image is missing? Otherwise, if you knew the missing index, *ngIf="i != knownIndex" or if imgSrc is blank (missing) *ngIf="item.imgSrc"
    – silentsod
    Nov 3, 2016 at 17:04
  • @silentsod thanks for your reply. I forgot to mention that I don´t know the missing index, I only get 404 error when trying to fetch the image.
    – doorman
    Nov 3, 2016 at 17:07

1 Answer 1

3

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>

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.