Skip to content

Instantly share code, notes, and snippets.

@e-oz
Created August 1, 2023 10:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save e-oz/a6beea4c1f21a4f92ee87ed29dc498d9 to your computer and use it in GitHub Desktop.
Save e-oz/a6beea4c1f21a4f92ee87ed29dc498d9 to your computer and use it in GitHub Desktop.
import { inject, TemplateRef, ViewContainerRef } from "@angular/core";
export abstract class StructuralConditionalDirective {
protected readonly templateRef = inject(TemplateRef<any>);
protected readonly viewContainer = inject(ViewContainerRef);
protected elseTemplateRef: TemplateRef<any> | undefined = undefined;
protected hasView: boolean = false;
protected hasElseView: boolean = false;
protected condition: boolean = false;
public setCondition(condition: boolean) {
this.condition = condition;
this.updateContainer();
}
public setElseTemplate(template: TemplateRef<any>) {
this.elseTemplateRef = template;
this.updateContainer();
}
private clearContainer() {
this.viewContainer.clear();
this.hasView = false;
this.hasElseView = false;
}
private updateContainer() {
if (this.condition) {
if (!this.hasView) {
this.clearContainer();
if (this.templateRef) {
this.viewContainer.createEmbeddedView(this.templateRef);
this.hasView = true;
}
}
} else {
if (!this.hasElseView) {
this.clearContainer();
if (this.elseTemplateRef) {
this.viewContainer.createEmbeddedView(this.elseTemplateRef);
this.hasElseView = true;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment