Angular2:如果img src无效,则显示占位符图像 [英] Angular2: Show placeholder image if img src is not valid

查看:172
本文介绍了Angular2:如果img src无效,则显示占位符图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标:使用动态源加载图像.如果找不到图像,请改为加载占位符图像.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆