Created
July 15, 2020 21:49
-
-
Save RaschidJFR/6af05918909647ae61417beae8d26b70 to your computer and use it in GitHub Desktop.
Angular spinner directive for loading images
This file contains hidden or 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, Renderer2, ElementRef, HostListener } from '@angular/core'; | |
@Directive({ | |
selector: 'img[ngxImgSpinner]', | |
exportAs: 'ngxImgSpinner' | |
}) | |
export class ImgSpinnerDirective { | |
private _loading = true; | |
private _error = false; | |
constructor( | |
private renderer: Renderer2, | |
private el: ElementRef) { | |
} | |
get error(): boolean { return this._error; } | |
get loading(): boolean { return this._loading; } | |
set loading(val: boolean) { | |
if (val) | |
this.renderer.addClass(this.el.nativeElement, 'loading'); | |
else | |
this.renderer.removeClass(this.el.nativeElement, 'loading'); | |
this._loading = val; | |
} | |
@HostListener('loadstart') onLoadStart() { | |
this.loading = true; | |
} | |
@HostListener('load') onLoad() { | |
this.loading = false; | |
this.renderer.addClass(this.el.nativeElement, 'loaded'); | |
} | |
@HostListener('error') onError() { | |
this.loading = false; | |
this._error = true; | |
this.renderer.addClass(this.el.nativeElement, 'error'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment