angular directive for Intersection Observer api

  angular

i try to implement infinte scroll with Intersectio Observer

with this directive

    import {
  AfterViewInit,
  Directive,
  ElementRef,
  EventEmitter,
  OnDestroy,
  Output
} from '@angular/core';

@Directive({
  selector: '[catOnVisible]'
})
export class OnVisibleDirective implements AfterViewInit, OnDestroy {
  @Output() public visible: EventEmitter<any> = new EventEmitter();

  private intersectionObserver?: IntersectionObserver;

  constructor(private element: ElementRef) {}

  public ngAfterViewInit(): void {
    this.intersectionObserver = new IntersectionObserver((entries) => {
      this.checkForIntersection(entries);
    }, {});
    this.intersectionObserver.observe(this.element.nativeElement as Element);
  }

  public ngOnDestroy(): void {
    this.intersectionObserver?.disconnect();
  }

  private checkForIntersection(
    entries: Array<IntersectionObserverEntry>
  ): void {
    entries.forEach((entry: IntersectionObserverEntry) => {
      const isIntersecting =
        (entry as any).isIntersecting &&
        entry.target === this.element.nativeElement;

      if (isIntersecting) {
        this.visible.emit();
      }
    });
  }
}

Then i try to console log on scroll method

<div (catOnVisible)="onScroll()">My target</div>

Nothing happens but i think is about missing part (https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API)

  let options = {
   root: document.querySelector('#scrollArea'),
   rootMargin: '0px',
   threshold: 1.0
}

How can implement the configuration above in my app?

Source: Angular Questions

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.