All files / src/app/core/directives intersection-observer.directive.ts

28.57% Statements 4/14
60% Branches 3/5
0% Functions 0/3
28.57% Lines 4/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 432x 2x   2x                   2x                                                          
import { DestroyRef, Directive, ElementRef, EventEmitter, Input, OnInit, Output, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
 
import { IntersectionStatus, fromIntersectionObserver } from './intersection-observer-util';
 
/**
 * detect visibility status of components via IntersectionObserver
 *
 * taken from: https://blog.bitsrc.io/angular-maximizing-performance-with-the-intersection-observer-api-23d81312f178
 */
@Directive({
  selector: '[ishIntersectionObserver]',
})
export class IntersectionObserverDirective implements OnInit {
  @Input() intersectionDebounce = 0;
  @Input() intersectionRootMargin = '0px';
  @Input() intersectionRoot: HTMLElement;
  @Input() intersectionThreshold: number | number[];
 
  @Output() visibilityChange = new EventEmitter<IntersectionStatus>();
 
  private destroyRef = inject(DestroyRef);
 
  constructor(private element: ElementRef) {}
 
  ngOnInit() {
    Iif (!SSR) {
      const element = this.element.nativeElement;
      const config = {
        root: this.intersectionRoot,
        rootMargin: this.intersectionRootMargin,
        threshold: this.intersectionThreshold,
      };
 
      fromIntersectionObserver(element, config, this.intersectionDebounce)
        .pipe(takeUntilDestroyed(this.destroyRef))
        .subscribe(status => {
          this.visibilityChange.emit(status);
        });
    }
  }
}