Created
July 3, 2020 07:58
-
-
Save xxzefgh/f3c08650147e423b9855b4110bd5c1a5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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