UNPKG

mcm-lazyload-image

Version:

Lazy load image directive to angular

66 lines (59 loc) 2.33 kB
import { Directive, ElementRef, HostListener, Input, OnInit } from '@angular/core'; import { AppAssets } from './app-assets'; /** * @name MCMLazyLoadImage * @description * LAZY LOAD DIRECTIVE, WHILE IMAGE IS LOAD SHOW A PLACEHOLDER, IF AN ERROR OCCURS SHOW A ERROR IMAGE. * Have 2 default images. * @author * Bryan Castro MCM - Mobile Developer {@link https://linkedin.com/in/bryan-castro-ec} */ @Directive({ selector: '[mcmLazyLoadImg]' }) export class MCMLazyLoadImgDirective implements OnInit { /** @param {string} defaultImage Path of the locale image that can be used how Placeholder while image in [src] attribute is loaded */ @Input() defaultImage = AppAssets.default; /** @param {string} errorImage Path of the locale image that appear when image failed to load. */ @Input() errorImage = AppAssets.errImage; imgElement!:HTMLImageElement; constructor( private imageRef: ElementRef, ) { this.imgElement = this.imageRef.nativeElement as HTMLImageElement; this.imgElement.setAttribute('loading', 'lazy'); this.setPlaceholderImage(); } ngOnInit(): void { if(this.errorImage == '' || !this.errorImage) this.errorImage = AppAssets.errImage; if(this.defaultImage == '' || !this.defaultImage ) this.defaultImage = AppAssets.default; } /** * @description * Sets the placeholder image for the img element. */ setPlaceholderImage(): void { this.imgElement.style.backgroundImage = `url(${this.defaultImage})`; this.imgElement.style.backgroundRepeat = 'no-repeat'; this.imgElement.style.backgroundPosition = 'center'; this.imgElement.style.backgroundSize = 'cover'; this.imgElement.style.transition = 'all .4s linear'; } /** * @description * A function that is triggered when the 'load' event is fired on the host element. * When url image has been loaded remove image placeholder. */ @HostListener('load', ['$event']) onLoadImage() { this.imgElement.style.backgroundImage = ''; } /** * Handles the 'error' event for the host listener. * When url image have an error when loading add image error default */ @HostListener('error', ['$event']) onErrImage() { this.imgElement.src = this.errorImage; this.imgElement.style.objectFit = 'cover'; this.imgElement.style.transition = 'all .4s linear'; } }