Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a variable in a template in Angular

Tags:

html

angular

I have the following template :

<div>   <span>{{aVariable}}</span> </div> 

and would like to end up with :

<div "let a = aVariable">   <span>{{a}}</span> </div> 

Is there a way to do it ?

like image 854
Scipion Avatar asked Jul 26 '16 06:07

Scipion


People also ask

What is template variable in Angular?

Template Reference Variable in angular is used to access all the properties of any element inside DOM. It can also be a reference to an Angular component or directive or a web component.

How do I get the template reference variable in component?

To get started using template reference variables, simply create a new Angular component or visit an existing one. To create a template reference variable, locate the HTML element that you want to reference and then tag it like so: #myVarName .


1 Answers

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

  • Where does Angular 4 define "as local-var" behavior for *ngIf?

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.

like image 66
yurzui Avatar answered Oct 20 '22 06:10

yurzui