Last active
March 24, 2021 12:03
-
-
Save yoSteve/560fb25e95bf38595abf0aa5c4dc1f91 to your computer and use it in GitHub Desktop.
*ngLet Structural 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
export class NgLetContext<T = any> { | |
$implicit: T = null!; | |
ngLet: T = null!; | |
} | |
@Directive({ | |
selector: '[ngLet]', | |
}) | |
export class NgLetDirective<T> implements OnInit { | |
private _context = new NgLetContext<T>(); | |
@Input() | |
set ngLet(value: T) { | |
this._context.$implicit = this._context.ngLet = value; | |
} | |
constructor(private _vcr: ViewContainerRef, private _templateRef: TemplateRef<NgLetContext>) {} | |
static ngTemplateContextGuard<T>(dir: NgLetDirective<T>, ctx: unknown): ctx is NgLetContext<T> { | |
return true; | |
} | |
ngOnInit() { | |
this._vcr.createEmbeddedView(this._templateRef, this._context); | |
} | |
} | |
/* | |
* Used in Template like this: | |
* | |
* <ng-container *ngLet="(a$| async) as a"> | |
* one thing: {{ a.one }} | |
* another: {{ a.another }} | |
* </ng-container> | |
* | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good for when you want to avoid multiple subscriptions but for whatever reason *ngIf won't do the trick.