Skip to content

Instantly share code, notes, and snippets.

@manbearwiz
Created November 1, 2023 04:10
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 manbearwiz/4ff86b60b8f55ee92052666ffd284fcf to your computer and use it in GitHub Desktop.
Save manbearwiz/4ff86b60b8f55ee92052666ffd284fcf to your computer and use it in GitHub Desktop.
An angular utility class for conditionally creating and destroying views.
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