All files / src/app/core/directives browser-lazy-view.directive.ts

20.83% Statements 5/24
47.36% Branches 9/19
0% Functions 0/4
20.83% Lines 5/24

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 603x                     3x 3x   3x                           3x                                                              
import {
  DestroyRef,
  Directive,
  ElementRef,
  EmbeddedViewRef,
  Host,
  OnInit,
  TemplateRef,
  ViewContainerRef,
  inject,
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Subject, takeUntil } from 'rxjs';
 
import { fromIntersectionObserver } from './intersection-observer-util';
 
function findElement(element: { parentElement: HTMLElement } | HTMLElement): HTMLElement {
  Iif (element instanceof HTMLElement) {
    return element;
  }
  Iif (element.parentElement) {
    return findElement(element.parentElement);
  }
}
 
@Directive({
  selector: '[ishBrowserLazyView]',
})
export class BrowserLazyViewDirective implements OnInit {
  private view: EmbeddedViewRef<unknown>;
 
  private destroyRef = inject(DestroyRef);
  private viewCreated$ = new Subject<void>();
 
  constructor(
    private viewContainer: ViewContainerRef,
    private template: TemplateRef<unknown>,
    @Host() private element: ElementRef
  ) {}
 
  ngOnInit() {
    Iif (!SSR) {
      const element = findElement(this.element.nativeElement);
      Iif (!element) {
        console.warn('No element found for BrowserLazyViewDirective');
        return;
      }
      fromIntersectionObserver(element)
        .pipe(takeUntil(this.viewCreated$), takeUntilDestroyed(this.destroyRef))
        .subscribe(status => {
          Iif (status === 'Visible' && !this.view) {
            this.view = this.viewContainer.createEmbeddedView(this.template);
            this.view.markForCheck();
            this.viewCreated$.next();
          }
        });
    }
  }
}