San*_*gde 61 typescript angular2-services angular
我想在HTML页面中使用组件的静态变量.如何将组件的静态变量与角度2中的HTML元素绑定?
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"
}
}
Run Code Online (Sandbox Code Playgroud)
<div>
url works!
{{urlArray}}
</div >
Run Code Online (Sandbox Code Playgroud)
Gün*_*uer 92
组件模板中的绑定表达式的范围是组件类实例.
你不能直接引用全局变量或静态.
作为解决方法,您可以向组件类添加getter
export class UrlComponent {
static urlArray;
constructor() {
UrlComponent.urlArray = "Inside Contructor";
}
get staticUrlArray() {
return UrlComponent.urlArray;
}
}
Run Code Online (Sandbox Code Playgroud)
并使用它像:
<div>
url works! {{staticUrlArray}}
</div>
Run Code Online (Sandbox Code Playgroud)
小智 27
要避免Angular调用在每个循环中获取staticUrlArray,可以在组件的公共范围中保存类引用:
export class UrlComponent {
static urlArray;
public classReference = UrlComponent;
constructor() {
UrlComponent.urlArray = "Inside Contructor";
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以直接使用它:
<div>
url works! {{ classReference.urlArray }}
</div>
Run Code Online (Sandbox Code Playgroud)
您也可以只声明类类型的字段,如下所示:
export class UrlComponent {
static urlArray;
UrlComponent = UrlComponent;
constructor() {
UrlComponent.urlArray=" Inside Contructor"
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用以下前缀引用静态变量:
<div>
url works! {{UrlComponent.urlArray}}
</div>
Run Code Online (Sandbox Code Playgroud)
这对于直接在模板中引用诸如枚举之类的东西或诸如控制台之类的对象也是必要的。
| 归档时间: |
|
| 查看次数: |
55323 次 |
| 最近记录: |