How to bind static variable of component in HTML in angular 2? How to bind static variable of component in HTML in angular 2? angular angular

How to bind static variable of component in HTML in angular 2?


The scope of binding expressions in a components template is the components class instance.

You can't refer to globals or statics directly.

As a workaround you can add a getter to your components class

export class UrlComponent {  static urlArray;  constructor() {    UrlComponent.urlArray = "Inside Contructor";  }  get staticUrlArray() {    return UrlComponent.urlArray;  }}

and use it like:

<div>  url works! {{staticUrlArray}}</div>


To avoid Angular calling get staticUrlArray at each cycle, you can save a class reference in the public scope of the component:

export class UrlComponent {  static urlArray;  public classReference = UrlComponent;  constructor() {    UrlComponent.urlArray = "Inside Contructor";  }}

And then you can use it directly:

<div>  url works! {{ classReference.urlArray }}</div>


You can also just declare a field of the class type, as such:

export class UrlComponent {  static urlArray;  UrlComponent = UrlComponent;    constructor() {    UrlComponent.urlArray=" Inside Contructor"  }}

You can then reference static variables using this prefix:

<div>  url works! {{UrlComponent.urlArray}}</div>

This also works / is necessary to reference stuff like Enums or objects like console directly in your template.