The goal of this article is to create a directive for lazy loading images after they enter the viewport.
@Directive({
selector: 'img[appLazyLoad]'
})
export class LazyLoadDirective implements AfterViewInit {
// ...
constructor(private el: ElementRef) {}
private lazyLoadImage() {
const obs = new IntersectionObserver(entries => {
entries.forEach(({ isIntersecting }) => {
if (isIntersecting) {
this.loadImage();
obs.unobserve(this.el.nativeElement);
}
});
});
obs.observe(this.el.nativeElement);
}
private loadImage() {
this.srcAttr = this.src;
}
}