I've created a custom component that uses a placeholder image if the image is still not loaded or if an error occurs when loading it:
img.component.ts:
import { Component, Input, OnChanges } from '@angular/core';
@Component({
selector: 'my-img',
templateUrl: 'img.component.html',
})
export class ImgComponent implements OnChanges {
@Input()
public src: string;
@Input()
public default: string;
@Input()
public alt: string;
public cached = false;
public loaded = false;
public error = false;
private lastSrc: string;
constructor() { }
public ngOnChanges() {
if (this.src !== this.lastSrc) {
this.lastSrc = this.src;
this.loaded = false;
this.error = false;
this.cached = this.isCached(this.src);
}
if (!this.src) {
this.error = true;
}
}
public onLoad() {
this.loaded = true;
}
public onError() {
this.error = true;
}
private isCached(url: string): boolean {
if (!url) {
return false;
}
let image = new Image();
image.src = url;
let complete = image.complete;
// console.log('isCached', complete, url);
return complete;
}
}
img.component.html:
<ng-container *ngIf="!cached">
<img
*ngIf="!error"
[hidden]="!loaded"
[src]="src"
[alt]="alt"
(load)="onLoad()"
(error)="onError()"
>
<img
*ngIf="default && (error || !loaded)"
[src]="default"
[alt]="alt"
>
</ng-container>
<ng-container *ngIf="cached">
<img
*ngIf="!error"
[src]="src"
[alt]="alt"
(error)="onError()"
>
<img
*ngIf="default && error"
[src]="default"
[alt]="alt"
>
</ng-container>
Then you can use it like:
<my-img [src]="src" [alt]="alt" [default]="DEFAULT_IMAGE"></my-img>
PS: I verify beforehand if the image is cached to avoid the image blinking (normally when a component that has the image inside is re-rendered) between the placeholder and the image (if it is cached, I show the image even before the loaded flag be set to true). You can uncomment the log in the isCached
function to see if your images are cached or not.