Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to declare a variable in a template in 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 ?
by

3 Answers

rahul07

<div ngFor="let a of [aVariable]">
<span>{{a}}</span>
</div>

When used with async pipe:

<div
ngFor="let a of [aVariable | async]">
<span>{{a.prop1}}</span>
<span>{{a.prop2}}</span>
</div>
kshitijrana14
It is much simpler, no need for anything additional. In my example I declare variable "open" and then use it.

<mat-accordion class="accord-align" #open>
<mat-expansion-panel hideToggle="true" (opened)="open.value=true" (closed)="open.value=false">
<mat-expansion-panel-header>
<span class="accord-title">Review Policy Summary</span>
<span class="spacer"></span>
<a ngIf="!open.value" class="f-accent">SHOW</a>
<a
ngIf="open.value" class="f-accent">HIDE</a>
</mat-expansion-panel-header>
<mat-divider></mat-divider>
<!-- Quote Details Component -->
<quote-details [quote]="quote"></quote-details>
</mat-expansion-panel>
</mat-accordion>
pankajshivnani123
Here is a directive I wrote that expands on the use of the exportAs decorator parameter, and allows you to use a dictionary as a local variable.

import { Directive, Input } from "@angular/core";
@Directive({
selector:"[localVariables]",
exportAs:"localVariables"
})
export class LocalVariables {
@Input("localVariables") set localVariables( struct: any ) {
if ( typeof struct === "object" ) {
for( var variableName in struct ) {
this[variableName] = struct[variableName];
}
}
}
constructor( ) {
}
}

You can use it as follows in a template:

<div #local="localVariables" [localVariables]="{a: 1, b: 2, c: 3+2}">
<span>a = {{local.a}}</span>
<span>b = {{local.b}}</span>
<span>c = {{local.c}}</span>
</div>

Of course #local can be any valid local variable name.

Login / Signup to Answer the Question.