Skip to content

Instantly share code, notes, and snippets.

@xxzefgh
Created July 3, 2020 07:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xxzefgh/f3c08650147e423b9855b4110bd5c1a5 to your computer and use it in GitHub Desktop.
Save xxzefgh/f3c08650147e423b9855b4110bd5c1a5 to your computer and use it in GitHub Desktop.
import {Directive, Input, HostListener} from '@angular/core';
@Directive({
selector: 'img[fallback]'
})
export class ImageFallbackDirective {
private _fallback = 'assets/images/404_image.png';
@Input() set fallback(value: string) {
if (value && value.length > 0) {
this._fallback = value;
}
}
@HostListener('error', ['$event']) onError(event: Event) {
const target = event.target as HTMLImageElement;
// avoid calling onerror if fallback image fails
if (target.dataset.fallback != this._fallback) {
target.src = target.dataset.fallback = this._fallback;
}
}
constructor() {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment