import { Directive, Input, TemplateRef, ViewContainerRef, inject } from "@angular/core";

//example usage
//<div *ngVar="false; let variable">
//<div *ngVar="{ x: 4 } as variable">

@Directive({
  selector: '[ngVar]'
})
export class VariableDirective {
  private templateRef = inject<TemplateRef<unknown>>(TemplateRef);
  private vcRef = inject(ViewContainerRef);

  @Input()
  set ngVar(context: unknown) {
    this.context.$implicit = this.context.ngVar = context;

    if (!this.hasView) {
      this.vcRef.createEmbeddedView(this.templateRef, this.context);
      this.hasView = true;
    }
  }

  private context: {
    $implicit: unknown;
    ngVar: unknown;
  } = {
      $implicit: null,
      ngVar: null,
    };

  private hasView: boolean = false;
}
