Last active
November 24, 2021 08:36
-
-
Save KEIII/e55c99baceb89c0afb32d6bd528e7ca7 to your computer and use it in GitHub Desktop.
Missed Angular *ngVar directive (from https://stackoverflow.com/a/43172992/1847657)
This file contains 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
// tslint:disable:no-any directive-selector | |
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core'; | |
/** | |
* Declare a variable in the template. | |
* Eg. <i *ngVar="false as variable">{{ variable | json }}</i> | |
*/ | |
@Directive({selector: '[ngVar]'}) | |
export class NgVarDirective { | |
public context: any = {}; | |
constructor( | |
private vcRef: ViewContainerRef, | |
private templateRef: TemplateRef<any>, | |
) {} | |
@Input() | |
set ngVar(context: any) { | |
this.context.$implicit = this.context.ngVar = context; | |
this.updateView(); | |
} | |
private updateView() { | |
this.vcRef.clear(); | |
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
If anyone cares, here is a version, that will retain the type of the variable inside the template: