Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...