Display Fallback Image On Angular Error Event

September 7, 2020 • • Published By • 2 minute read

Images on the web don’t always load for a number of reasons. Instead of seeing an ugly broken image, let’s learn how to display a fallback image if the original fails to load.

Table of Contents

Angular Template Variable

A typical Angular template that displays an image may look like the example below. The src attribute defines the image url, which in the below example is a variable called imageUrl.

<img [src]="imageUrl">

Add an Angular template variable to the image tag. Template variables are prefixed with #. In the below example, the template variable is #img. This provides a local variable representing the image tag.

<img #img [src]="imageUrl">

Add the error event to the image tag. If the image fails to load, it will use the local template variable to override the src attribute with a default image url!

<img #img [src]="imageUrl" (error)="img.src = defaultImageUrl">

Angular Directive

To make things easier, let’s create an Angular Directive, specifically an attribute directive for the img tag. It will listen for the error event using the HostListener decorator. If an error occurs, it will change the image src to either the path passed in or the default path.

import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({
    selector: 'img[appImgFallback]'
})
export class ImgFallbackDirective {

    constructor(private element: ElementRef) {}

    @Input('appImgFallback') fallback: string;

    @HostListener('error')
    displayFallbackImg() {
        this.element.nativeElement.src = this.fallback || './assets/fallback.png';
    }

}

Remove the template variable and error event listener. Add the new appImgFallback directive!

<img [src]="imageUrl" appImgFallback>

You can also pass in a path to an image if you don’t want to use the fallback defined in the directive!

<img [src]="imageUrl" appImgFallback="path/to/some/image">
Related Articles
About the Author

Front End Developer

https://nightwolf.dev