Skip to content

Instantly share code, notes, and snippets.

@yoSteve
Last active March 24, 2021 12:03
Show Gist options
  • Save yoSteve/560fb25e95bf38595abf0aa5c4dc1f91 to your computer and use it in GitHub Desktop.
Save yoSteve/560fb25e95bf38595abf0aa5c4dc1f91 to your computer and use it in GitHub Desktop.
*ngLet Structural Directive
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>
*
*/
@yoSteve
Copy link
Author

yoSteve commented Mar 24, 2021

Good for when you want to avoid multiple subscriptions but for whatever reason *ngIf won't do the trick.

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