DEV Community

Travis
Travis

Posted on

Replacing "broken" images in Angular with a default image

Replacing “broken” images in Angular with a default image

Did you know broken images handle like errors, even if they do not actually log an error?

Images can fail to load for a number of reasons; the server is down, internet connection is suspect, or occasionally in tapping into an API endpoint for images, we GET an image src that turns out to be bad.

In this example, I will demonstrate a quick and easy fix for substituting a broken image with a default image.

The Problem

Here I have a slide with an image that has failed to load.

Image description

Upon further inspection in the console, we can see there is a src for that image:

Image description

Diving even deeper, we can see inside the network tab that the image comes through as 200, Status OK

So, what’s the problem? In this case, the src was bad and we are hostage to what the API returns.

The Solution

The solution in this case was to place an event listener on the image and use logic to replace broken images with a default image:

In my TS file for the component, I add a property for a defaultImg:

defaultImage: string = '../src/for/a/good/image'
Enter fullscreen mode Exit fullscreen mode

In my HTML Template, I add the event listner and substitution logic.

<img [src]="slide.image [alt]="slide.title" (error)="slide.image = defaultImage">
Enter fullscreen mode Exit fullscreen mode

Here we are using Angular's built in event listener for error(error) and changing slide.image to defaultImage when there is an error loading the image:

Image description

Supplemental

You may also wish to set the error to null inside the event in case your backup image also fails to prevent an infinite loop.

Top comments (0)