Setting a default image in Html when the image unable to load (Angular)

Image Frames
Image Frames

Many time we want to set default image in html image tag when it unable to load given image. We can achieve this in angular as well as in HTML.

In Angular

// a.html file
<img [src]='path' (error) ="onImgError($event)">

// a.ts file
onImgError(event) { 
    event.target.src = 'assets/path_to_your_placeholder_image.jpg';
}

OR

<img [src]='path' (error) ="$event.target.src = 'assets/path_to_your_image.jpg'">

OR

In Html

<img src='path' onerror ="this.src = 'assets/path_to_your_placeholder_image.jpg'">

It might happen that your alternate image is also not available above code stuck in infinite loop. To avoid this we can improve above code like this

<img src="path" onerror="this.src=assets/path_to_your_placeholder_image.jpg';this.onerror='';">

Leave a Reply