How do I change the source of an image if an error

2020-04-18 07:41发布

问题:

Why does the following statement throw an error?

Idea: To show an image from the normal URL. If it's not found (404), show a fallback image.

Work Done:

<img [src]='image_path + item.leafname' (error) ="[src] = 'fallback_path + item.leafname'" height="200px" class="card-img-top">

Error thrown:

Parser Error: Unexpected token '=' at column 7 in [[src] = 'image_path + item.leafname'] in ng:///AppModule/DashboardComponent.html@46:60

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?

回答1:

You should implement this logic in the component, not in the template.

Then change your template like so:

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



回答2:

Try this:

if(typeof(src)==="undefined")
{
$("#imageID").attr("src","yourNewSource_goes_here");
}

If that doesn't work, you can try this:

if(document.getElementById("myImg").complete==false)
{
$("#myImg").attr("src","another_source_goes_here");
}


标签: angular