I am fetching a large number of image URLs from an API and display them in a angular 2 web application. Some of the URLs are broken and i want to replace them with a default
A perfect Angular 8 directive:
import {AfterViewInit, Directive, ElementRef, Input} from '@angular/core';
@Directive({
selector: '[appImage]'
})
export class ImageDirective implements AfterViewInit {
@Input() src;
constructor(private imageRef: ElementRef) {
}
ngAfterViewInit(): void {
const img = new Image();
img.onload = () => {
this.setImage(this.src);
};
img.onerror = () => {
// Set a placeholder image
this.setImage('assets/placeholder.png');
};
img.src = this.src;
}
private setImage(src: string) {
this.imageRef.nativeElement.setAttribute('src', src);
}
}
Now, HTML will be: