Last active
June 30, 2020 14:41
-
-
Save jschwarty/3363a2e0300f90003893cee8619859bd to your computer and use it in GitHub Desktop.
Angular ngLet directive
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
// 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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
<section *ngLet="data$ | async as data"></section>