How to declare a variable in a template in Angular

Forums AngularHow to declare a variable in a template in Angular
Staff asked 4 weeks ago

Answers (1)

Add Answer
monika gabani Marked As Accepted
Staff answered 4 weeks ago

We can just create directive like *ngIf and call it *ngVar

    selector: '[ngVar]',
export class VarDirective {
  set ngVar(context: any) {
    this.context.$implicit = this.context.ngVar = context;

  context: any = {};

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

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

with this *ngVar directive we can use the following

<div *ngVar="false as variable">
      <span>{{variable | json}}</span>



<div *ngVar="false; let variable">
    <span>{{variable | json}}</span>

you can also deal wit h template variable as below:

<div *ngIf="{ a: 1, b: 2 }; let variable">



Select Categories