Skip to content

Instantly share code, notes, and snippets.

@marianocodes
Last active February 11, 2018 04:42
Show Gist options
  • Save marianocodes/f634655d4636446ff4f7571d21d8beaa to your computer and use it in GitHub Desktop.
Save marianocodes/f634655d4636446ff4f7571d21d8beaa to your computer and use it in GitHub Desktop.
Ionic 3 example
import {
Directive,
ElementRef,
EventEmitter,
Input,
Output,
OnInit, OnDestroy, Renderer2
} from '@angular/core';
import { ImgCacheService } from './img-cache.service';
import { Subscription } from 'rxjs/Subscription';
/**
* This directive is charge of cache the images and emit a loaded event
*/
@Directive({
selector: '[op-lazy-img]'
})
export class LazyLoadDirective implements OnInit, OnDestroy {
@Input('source')
public source: string = '';
@Output()
public loaded: EventEmitter<void> = new EventEmitter<void>();
public loadListener: () => void;
public errorListener: () => void;
private cacheSubscription: Subscription;
constructor(public el: ElementRef,
public imgCacheService: ImgCacheService,
public renderer: Renderer2) { }
public ngOnInit(): void {
// get img element
const nativeElement: HTMLElement = this.el.nativeElement;
// add load listener
this.loadListener = this.renderer.listen(nativeElement, 'load', () => {
this.renderer.addClass(nativeElement, 'loaded');
this.loaded.emit();
});
this.errorListener = this.renderer.listen(nativeElement, 'error', () => {
nativeElement.remove();
});
// cache img and set the src to the img
this.cacheSubscription =
this.imgCacheService
.cache(this.source)
.subscribe((value) => {
this.renderer.setAttribute(nativeElement, 'src', value);
}, (e) => console.log(e));
}
public ngOnDestroy(): void {
// remove listeners
this.loadListener();
this.errorListener();
this.cacheSubscription.unsubscribe();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment