1

I have followed a tutorial in about creating a custom directive for lazy loading an image in angular 8 as so:

import { AfterViewInit, Directive, ElementRef, HostBinding, Input } from '@angular/core';

@Directive({
  selector: 'img[appLazyLoad]'
})
export class LazyLoadDirective implements AfterViewInit {
  @HostBinding('attr.src') srcAttr = null;
  @Input() src: string;

  constructor(private el: ElementRef) {}

  ngAfterViewInit() {
    this.canLazyLoad() ? this.lazyLoadImage() : this.loadImage();
  }

  private canLazyLoad() {
    return window && 'IntersectionObserver' in window;
  }

  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;
  }
}

I have a component that should render multiple images (I was thinking of creating an array for the "src") and I would like to use this directive so the images won't load all at the same time. In the tutorial where I got this code, it doesn't say how I can use it. Could you please tell me how to use it. Thank you!

Wasim
  • 600
  • 2
  • 11
  • 32
Ibanez1408
  • 4,550
  • 10
  • 59
  • 110

0 Answers0