Angular2:如果img src无效,则显示占位符图像 [英] 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.
这应该演示我正在尝试做的事情,但是我不知道如何根据第一个img
src
是否有效来有条件地设置validImage
.
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="...">
如果src="./app/assets/images/{{image.ID}}.jpg"
返回图像,则
validImage
应该为true
.否则,它将返回false
并且仅显示第二个img
标记.
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.
对于在Angular2中实现此目标的最佳方法的任何建议,将不胜感激.
Any suggestions on the best way to implement this in Angular2 would be greatly appreciated.
推荐答案
处理损坏的图像链接的最佳方法是对<img>
标签使用onError
事件:
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="..." />
这篇关于Angular2:如果img src无效,则显示占位符图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!