How to declare a variable in a template in Angular

Update

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

ng-var.directive.ts

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

        if (!this.hasView) {
            this.vcRef.createEmbeddedView(this.templateRef, this.context);
            this.hasView = true;
        }
    }

    private context: {
        $implicit: unknown;
        ngVar: unknown;
    } = {
        $implicit: null,
        ngVar: null,
    };

    private hasView: boolean = false;

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

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>

or

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

or

<div *ngVar="{ x: 4 } as variable">
    <span>{{variable | json}}</span>
</div>

Plunker Example Angular4 ngVar

See also

Original answer

Angular v4

  1. div + ngIf + let

    {{variable.a}}
    {{variable.b}}

  2. div + ngIf + as

view

<div *ngIf="{ a: 1, b: 2, c: 3 + x } as variable">
  <span>{{variable.a}}</span>
  <span>{{variable.b}}</span>
  <span>{{variable.c}}</span>
</div>

component.ts

export class AppComponent {
  x = 5;
}
  1. If you don’t want to create wrapper like div you can use ng-container

view

<ng-container *ngIf="{ a: 1, b: 2, c: 3 + x } as variable">
  <span>{{variable.a}}</span>
  <span>{{variable.b}}</span>
  <span>{{variable.c}}</span>
</ng-container>

As @Keith mentioned in comments

this will work in most cases but it is not a general solution since it
relies on variable being truthy

See update for another approach.

Leave a Comment