Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
116
rated 0 times [  121] [ 5]  / answers: 1 / hits: 82382  / 8 Years ago, wed, march 16, 2016, 12:00:00

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.


More From » angular

 Answers
15

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=... />

[#62929] Sunday, March 13, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
faithemilys

Total Points: 418
Total Questions: 100
Total Answers: 114

Location: North Korea
Member since Fri, Nov 4, 2022
2 Years ago
;