Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: Show placeholder image if img src is not valid

Goal: Load an image with a dynamic source. If no image is found, then load a placeholder image instead.

This should demonstrate what I'm trying to do, but I don't know how to conditionally set validImage based on whether the first img src is valid.

<img *ngif="validImage" class="thumbnail-image" src="./app/assets/images/{{image.ID}}.jpg" alt="..."> <img *ngif="!validImage" class="thumbnail-image" src="./app/assets/images/placeholder.jpg" alt="..."> 

validImage should be true if src="./app/assets/images/{{image.ID}}.jpg" returns an image. Otherwise it would return false and only the second img tag should show.

There are obvious work arounds like storing a list of all valid image sources, but I'm thinking there is a better way to accomplish this.

Any suggestions on the best way to implement this in Angular2 would be greatly appreciated.

like image 553
user2263572 Avatar asked Mar 16 '16 03:03

user2263572


People also ask

How do I know if my img src is valid?

To check if an img src is valid: Add an error event listener on the img element. If the src is invalid, set it to a backup image. Alternatively, hide the image.

How do I load a default image HTML image not found?

In HTML, this can be done with the onerror attribute of the <img> tag. If the original image fails to load, then it is replaced by the image mentioned in the onerror attribute handler.

How to handle image error in Angular?

In HTML, you can react to broken images at runtime by attaching a handler to the img element's error event. In Angular, you can do this in a directive that you can then simply apply to an img element without any additional code.

How do you add a fallback image in HTML?

HTML has no fallback for broken images. You'd need to use JavaScript to find broken images and change their src attribute. Actually, Firefox has a real fallback for images that don't load! It places the alternative Text of the image instead of the image, and even applies styling to it!


2 Answers

The best way to handle broken image links is the use the onError event for the <img> tag:

<img  class="thumbnail-image" src="./app/assets/images/{{image.ID}}.jpg"       onerror="this.src='./app/assets/images/placeholder.jpg';"  alt="..." /> 
like image 162
JanR Avatar answered Sep 21 '22 11:09

JanR


<img [src]="pic" (error)="setDefaultPic()"> 

And somewhere in your component class:

setDefaultPic() {   this.pic = "assets/images/my-image.png"; } 
like image 34
Tiago Bértolo Avatar answered Sep 17 '22 11:09

Tiago Bértolo