# All files / modules/in-view/src ngui-inview.directive.ts

68% Statements 17/25
54.55% Branches 12/22
50% Functions 3/6
68.18% Lines 15/22

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
    681x

    1x

    1x

    4x

    4x

    4x

    3x
    3x
    3x

    1x

    1x
    2x
    2x

    1x

    1x
     import {
      Directive,
      ElementRef,
      EventEmitter,
      Inject,
      Input,
      OnDestroy,
      OnInit,
      Output,
      PLATFORM_ID,
      Renderer2,
      ViewChild
    } 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]' // tslint:disable-line
    })
    export class NguiInviewDirective implements OnInit, OnDestroy {
      observer: IntersectionObserver;

      /** IntersectionObserver options */
      @Input() options: any = {};

      /** Event that will be fired when in viewport */
      @Output() nguiInview: EventEmitter<any> = new EventEmitter();
      /** Event that will be fired when out of  viewport */
      @Output() nguiOutview: EventEmitter<any> = new EventEmitter();

      constructor(
        public element: ElementRef,
        public renderer: Renderer2,
        @Inject(PLATFORM_ID) private platformId: any) {
      }

      /** Starts IntersectionObserver */
      ngOnInit(): void {
        if (isPlatformBrowser(this.platformId)) {
          this.observer = new IntersectionObserver(this.handleIntersect.bind(this), this.options);
          this.observer.observe(this.element.nativeElement);
        }
      }

      /** Stops IntersectionObserver */
      ngOnDestroy(): void {
        Eif (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, observer): void {
        entries.forEach((entry: IntersectionObserverEntry) => {
          if (entry['isIntersecting']) {
            this.nguiInview.emit(entry);
          } else {
            this.nguiOutview.emit(entry);
          }
        });
      }
    }