如果发生错误,如何更改图像的来源? [英] How do I change the source of an image if an error occurs?
问题描述
为什么以下语句会引发错误?
Why does the following statement throw an error?
想法:显示来自正常URL的图像.如果找不到(404),请显示后备图片.
Idea: To show an image from the normal URL. If it's not found (404), show a fallback image.
完成的工作:
<img [src]='image_path + item.leafname' (error) ="[src] = 'fallback_path + item.leafname'" height="200px" class="card-img-top">
引发错误:
Parser Error: Unexpected token '=' at column 7 in [[src] = 'image_path + item.leafname'] in ng:///AppModule/DashboardComponent.html@46:60
其他答案:
我在Stack上找到了其他答案,建议将ng-src
用于普通图像,将onerror = "this.src='url'"
用于后备图像.但是,如何使用[src]绑定和(错误)事件绑定来做同样的事情?
Other Answers:
I found alternative answers on Stack, which suggests using ng-src
for the usual image and onerror = "this.src='url'"
for a fallback image. But, how do I do the same using the [src] binding and (error) event binding?
推荐答案
您应在组件而不是模板中实现此逻辑.
You should implement this logic in the component, not in the template.
然后像这样更改模板:
<img [src]='image_path + item.leafname' (error) ="changeSource($event, item.leafname)">
然后创建一个错误处理程序,如下所示:
Then create an error handler, like so:
changeSource(event, name) { event.target.src = this.fallback_path + name; }
将图像源更新为后备源.
Which updates the image source to your fallback source.
这篇关于如果发生错误,如何更改图像的来源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!