All files / ngui-inview/src ngui-inview.directive.ts

95.23% Statements 20/21
85.71% Branches 6/7
100% Functions 5/5
94.73% Lines 18/19

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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 722x                     2x               2x       10x           10x   10x     10x 10x         4x       4x 4x 4x           11x 8x                 2x 2x 1x   1x          
import {
    Directive,
    ElementRef,
    EventEmitter,
    Inject,
    Input,
    OnDestroy,
    OnInit,
    Output,
    PLATFORM_ID
} from '@angular/core';
import {isPlatformBrowser} from '@angular/common';
 
/**
 * Fires (nguiInview) or (nguiOutview) events dependents on the element is in viewport or not
 */
@Directive({
    selector: '[nguiInview], [nguiOutview]' // eslint-disable-line
})
export class NguiInviewDirective implements OnInit, OnDestroy {
  observer: IntersectionObserver;
 
    /** IntersectionObserver options */
  @Input() observerOptions: IntersectionObserverInit = {threshold: [.1, .2, .3, .4, .5, .6, .7, .8]};
    /** Deprecated config. Use `observerOptions` instead.
     * @deprecated Use `observerOptions` instead. */
  @Input() options: any;
 
    /** Event that will be fired when in viewport */
  @Output() nguiInview: EventEmitter<IntersectionObserverEntry> = new EventEmitter();
    /** Event that will be fired when out of  viewport */
  @Output() nguiOutview: EventEmitter<IntersectionObserverEntry> = new EventEmitter();
 
  constructor(
        public element: ElementRef,
        @Inject(PLATFORM_ID) private platformId: any) {
  }
 
    /** Starts IntersectionObserver */
  ngOnInit(): void {
    Iif (this.options) {
      this.observerOptions = this.options;
    }
 
    if (isPlatformBrowser(this.platformId)) {
      this.observer = new IntersectionObserver(this.handleIntersect.bind(this), this.observerOptions);
      this.observer.observe(this.element.nativeElement);
    }
  }
 
    /** Stops IntersectionObserver */
  ngOnDestroy(): void {
    if (isPlatformBrowser(this.platformId) && this.observer) {
      this.observer.disconnect();
    }
  }
 
    /**
     * Fires (nguiInview) event when this element is in viewport
     *  and fires (nguiOutview) event when this element is not in viewport
     */
  handleIntersect(entries): void {
    entries.forEach((entry: IntersectionObserverEntry) => {
      if (entry['isIntersecting']) {
        this.nguiInview.emit(entry);
      } else {
        this.nguiOutview.emit(entry);
      }
    });
  }
}