Skip to content

Instantly share code, notes, and snippets.

@windwp
Created May 31, 2018 06:13
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 windwp/48faad05238c95c33256e10d7225d0ea to your computer and use it in GitHub Desktop.
Save windwp/48faad05238c95c33256e10d7225d0ea to your computer and use it in GitHub Desktop.
preload image angular directive
import { Directive, ElementRef, Input } from '@angular/core';
@Directive({
selector: '[preloadImage]'
})
export class PreloadImage {
private _sourceImage: string;
private _errorImage: string;
private
@Input('preloadImage') set sourceImage(url: string) {
this._sourceImage = url;
if (!url) return;
let img: HTMLImageElement = new Image();
if (img) {
img.onload = () => {
this.el.nativeElement.className = this.el.nativeElement.className.replace('loading', '');
this.el.nativeElement.className += ' loaded';
this.el.nativeElement.src = this._sourceImage;
img = null;
};
img.onerror = (data) => {
this.el.nativeElement.className = this.el.nativeElement.className.replace('loading', '');
this.el.nativeElement.className += ' error';
this.el.nativeElement.src = this._errorImage;
};
img.src = url;
this._sourceImage = url;
} else {
this.el.nativeElement.src = url;
}
}
@Input('errorImage') set errorImage(url: string) {
this._errorImage = url;
setTimeout(() => {
if (!this._sourceImage) {
this.el.nativeElement.className = this.el.nativeElement.className.replace('loading', '');
this.el.nativeElement.className += ' loaded';
this.el.nativeElement.src = this._errorImage;
}
}, 100)
}
constructor(private el: ElementRef) {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment