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

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

  context: any = {};

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

  updateView() {
    this.vcRef.clear();
    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>

 

or

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

you can also deal wit h template variable as below:

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

 

Subscribe

Select Categories