Handle missing images in Angular
When displaying images in an Angular application (or any other web application), you need to ensure that the images exist so that the placeholder for the broken image is not rendered by the browser.
However, this is not possible if you do not have full control over the images that are displayed. In this case, you will not notice the absence of an image until the browser receives a 404 error in response to its requests.
There is no way to detect this error condition directly in the code. But fortunately, there is an error
event for the img
element that fires when this happens. In Angular, you can attach a handler to this event just like any other event:
<img [src]="image" class="image" (error)="handleMissingImage($event)" />
In the error handler, you can decide how to react to it. In the following example, I simply hide the image element to get rid of the browser placeholder for the broken image:
public handleMissingImage(event: Event) {
(event.target as HTMLImageElement).style.display = 'none';
}
In many cases, this may already be enough:
If needed, the code can easily be extended to display a different placeholder image by changing the value of the src
attribute or something else that matches your design.
If you need to handle missing images in your application in multiple components, you may want to avoid repeating the same markup and code everywhere. An Angular directive can help you do this:
import { Directive, ElementRef, HostListener } from "@angular/core";
@Directive({
selector: "img[appHideMissing]",
})
export class HideMissingDirective {
constructor(private el: ElementRef) {}
@HostListener("error")
private onError() {
this.el.nativeElement.style.display = "none";
}
}
The @HostListener
decorator is used to attach a handler to the error
event. The reference to the underlying element is injected into the constructor. The onError
handler takes care of hiding the element.
Instead of attaching a handler to each img
element, you can now simply use the directive in the markup without any additional code:
<img [src]="image" class="image" appHideMissing />
To see the code in action, check out my GitHub repository.
In HTML, you can react to broken images at runtime by attaching a handler to the img
element's error
event. In Angular, you can do this in a directive that you can then simply apply to an img
element without any additional code.