Skip to content

Instantly share code, notes, and snippets.

@jschwarty
Last active June 30, 2020 14:41
Show Gist options
  • Save jschwarty/3363a2e0300f90003893cee8619859bd to your computer and use it in GitHub Desktop.
Save jschwarty/3363a2e0300f90003893cee8619859bd to your computer and use it in GitHub Desktop.
Angular ngLet directive
// From https://stackblitz.com/edit/directive-collection-with-examples?file=src%2Fapp%2Fng-let.directive.ts
import {
Directive,
Input,
TemplateRef,
ViewContainerRef,
EmbeddedViewRef
} from "@angular/core";
@Directive({
selector: "[ngLet]"
})
export class LetDirective {
_ref: EmbeddedViewRef<any>;
context: any = {};
@Input()
set ngLet(value: any) {
// if embeadded view doesn't exist yet create it (only once)
if (!this._ref)
this.createView();
// if value is empty destroy the component
// here it's acctualy works like ngIf (will rerender on non-empty value)
if (!value) {
this._ref.destroy();
this._ref = undefined;
return;
}
// add the value to the context
this._ref.context.$implicit = this.context.ngLet = value;
}
constructor(
private readonly vcRef: ViewContainerRef,
private readonly templateRef: TemplateRef<any>
) {}
createView(): void {
this.vcRef.clear();
this._ref = this.vcRef.createEmbeddedView(this.templateRef, this.context);
}
}
@jschwarty
Copy link
Author

Usage:
<section *ngLet="data$ | async as data"></section>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment