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) { = 'assets/path_to_your_placeholder_image.jpg';


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


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='';">

This Post Has 2 Comments

  1. Rohit Pancholi

    it’s working ; )

    1. admin

      Nice to hear this.

Leave a Reply