File

libs/common/frame/src/core/sidebar-marker/sidebar-marker.directive.ts

Implements

OnInit OnDestroy

Metadata

import {
  Directive,
  EmbeddedViewRef,
  OnDestroy,
  OnInit,
  TemplateRef,
  ViewContainerRef,
  inject
} from '@angular/core';
import { Subject } from 'rxjs';
import { takeUntil, tap } from 'rxjs/operators';
import { TalyFrameSidebarService } from '../../services/sidebar.service';

@Directive({
  selector: '[talyFrameSidebar]',
  standalone: false
})
export class TalySidebarMarkerDirective implements OnInit, OnDestroy {
  private templateRef = inject<TemplateRef<unknown>>(TemplateRef);
  private viewContainer = inject(ViewContainerRef);
  private sidebarService = inject(TalyFrameSidebarService);

  private _currentViewRef: EmbeddedViewRef<unknown> | null = null;
  private _renderContent = true;
  private _destroy = new Subject<void>();

  ngOnDestroy() {
    this._destroy.next();
  }

  ngOnInit(): void {
    this.sidebarService.registerTemplate(this.templateRef);
    this.sidebarService.show$
      .pipe(
        takeUntil(this._destroy),
        tap((showSidebar) => {
          this._renderContent = showSidebar === false;
          this._renderComponent();
        })
      )
      .subscribe();
  }

  private _renderComponent() {
    if (this._renderContent && !this._currentViewRef) {
      this._currentViewRef = this.viewContainer.createEmbeddedView(this.templateRef);
    }

    if (!this._renderContent && this._currentViewRef) {
      this._currentViewRef.detach();
      this._currentViewRef.destroy();
      this._currentViewRef = null;
    }
  }
}

results matching ""

    No results matching ""