Created
November 1, 2023 04:10
-
-
Save manbearwiz/4ff86b60b8f55ee92052666ffd284fcf to your computer and use it in GitHub Desktop.
An angular utility class for conditionally creating and destroying views.
This file contains 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 { ViewContainerRef, TemplateRef, EmbeddedViewRef } from '@angular/core'; | |
/** | |
* A utility class for conditionally creating and destroying views. | |
*/ | |
export class ConditionalView<T = unknown> { | |
private _viewRef?: EmbeddedViewRef<T>; | |
/** | |
* Creates a new ConditionalView. | |
* @param _viewContainerRef - The view container to create the view in. | |
* @param _templateRef - The template to use for the view. | |
*/ | |
constructor( | |
private readonly _viewContainerRef: ViewContainerRef, | |
private readonly _templateRef: TemplateRef<T>, | |
) {} | |
/** | |
* Creates a view using the provided TemplateRef. | |
*/ | |
create(): void { | |
this._viewRef = this._viewContainerRef.createEmbeddedView( | |
this._templateRef, | |
); | |
} | |
/** | |
* Destroys the view if it exists. | |
*/ | |
destroy(): void { | |
if (this._viewRef) { | |
const index = this._viewContainerRef.indexOf(this._viewRef); | |
this._viewContainerRef.remove(index); | |
this._viewRef = undefined; | |
} | |
} | |
/** | |
* Enforces the state of the view. If the view is not created and should be, it will be created. If the view is created and should not be, it will be destroyed. | |
* @param created - Whether to create or destroy the view. | |
*/ | |
enforceState(created: boolean): void { | |
if (created && !this._viewRef) { | |
this.create(); | |
} else if (!created && this._viewRef) { | |
this.destroy(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment