Scipion Scipion - 4 months ago 52
HTML Question

How to declare a variable in a template in Angular2

I have the following template :


and would like to end up with :

<div "let a = aVariable">

Is there a way to do ?


This isn't supported.

There are template variables but it's not supported to assign arbitrary values. They can only be used to refer to the elements they are applied to, exported names of directives or components and scope variables for structural directives like ngFor,

See also


  selector: '[var]',
  exportAs: 'var'
class VarDirective {
  @Input() var:any;

and initialize it like

<div #aVariable="var" var="abc"></div>


<div #aVariable="var" [var]="'abc'"></div>

and use the variable like


(not tested)

  • #aVariable creates a reference to the VarDirective (`exportAs: 'var')
  • var="abc" instantiates the VarDirective and passes the string value "abc" to it's value input.
  • aVariable.var reads the value assigned to the var directives var input.