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.
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.
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.
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.
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!
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="..." />
<img [src]="pic" (error)="setDefaultPic()">
And somewhere in your component class:
setDefaultPic() { this.pic = "assets/images/my-image.png"; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With