https://github.com/angular/angular
Raw File
Tip revision: a8e57a1fabdd4773477bbc9ca5e6ebcd34140624 authored by Alex Rickabaugh on 02 November 2023, 22:00:59 UTC
release: cut the v17.0.0-rc.2 release
Tip revision: a8e57a1
if-loaded.directive.ts
import {Directive, Input, TemplateRef, ViewContainerRef} from '@angular/core';

import {Loaded, LoadingState} from './loading-state';

@Directive({
  standalone: true,
  selector: '[appIfLoaded]',
})
export class IfLoadedDirective<T> {
  private isViewCreated = false;

  @Input('appIfLoaded') set state(state: LoadingState<T>) {
    if (!this.isViewCreated && state.type === 'loaded') {
      this.viewContainerRef.createEmbeddedView(this.templateRef);
      this.isViewCreated = true;
    } else if (this.isViewCreated && state.type !== 'loaded') {
      this.viewContainerRef.clear();
      this.isViewCreated = false;
    }
  }

  constructor(
    private readonly viewContainerRef: ViewContainerRef,
    private readonly templateRef: TemplateRef<unknown>,
  ) {}

  static ngTemplateGuard_appIfLoaded<T>(
    dir: IfLoadedDirective<T>,
    state: LoadingState<T>,
  ): state is Loaded<T> {
    return true;
  }
}
back to top