Skip to content

Instantly share code, notes, and snippets.

@KEIII
Last active November 24, 2021 08:36
Show Gist options
  • Save KEIII/e55c99baceb89c0afb32d6bd528e7ca7 to your computer and use it in GitHub Desktop.
Save KEIII/e55c99baceb89c0afb32d6bd528e7ca7 to your computer and use it in GitHub Desktop.
Missed Angular *ngVar directive (from https://stackoverflow.com/a/43172992/1847657)
// 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);
}
}
@Akxe
Copy link

Akxe commented Nov 24, 2021

If anyone cares, here is a version, that will retain the type of the variable inside the template:

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';


interface VarContext<T> {
	$implicit: T;
	var: T;
}

/**
 * Declare a variable in the template.
 * Eg. <i *var="false as variable">{{ variable | json }}</i>
 */
@Directive({selector: '[var]'})
export class VarDirective<T = unknown> {
	public context: VarContext<T> = {} as any;

	constructor(
		private vcRef: ViewContainerRef,
		private templateRef: TemplateRef<any>,
	) {}

	@Input()
	set var(context: T) {
		this.context.$implicit = this.context.var = context;
		this.updateView();
	}

	private updateView() {
		this.vcRef.clear();
		this.vcRef.createEmbeddedView(this.templateRef, this.context);
	}

	static ngTemplateContextGuard<T>(dir: VarDirective<T>, ctx: any): ctx is VarContext<T> {
		return true;
	}
}

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