How to bind static variable of component in HTML in angular 2?
I want to use a static variable of a component in HTML page. How to bind static variable of component with a HTML element in angular 2?
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Rx';
@Component({
moduleId: module.id,
selector: 'url',
templateUrl: 'url.component.html',
styleUrls: ['url.component.css']
})
export class UrlComponent {
static urlArray;
constructor() {
UrlComponent.urlArray=" Inside Contructor"
}
}
<div>
url works!
{{urlArray}}
</div >
Solution 1:
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>
Solution 2:
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>
Solution 3:
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.