Created
August 1, 2023 10:14
-
-
Save e-oz/a6beea4c1f21a4f92ee87ed29dc498d9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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