Created
May 31, 2018 06:13
-
-
Save windwp/48faad05238c95c33256e10d7225d0ea to your computer and use it in GitHub Desktop.
preload image angular directive
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, 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