[英]How to bind static variable of component in HTML in angular 2?
我想在 HTML 頁面中使用組件的靜態變量。 如何將組件的靜態變量與 angular 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"
}
}
<div>
url works!
{{urlArray}}
</div >
組件模板中綁定表達式的范圍是組件類實例。
您不能直接引用全局變量或靜態變量。
作為一種解決方法,您可以在組件類中添加一個 getter
export class UrlComponent {
static urlArray;
constructor() {
UrlComponent.urlArray = "Inside Contructor";
}
get staticUrlArray() {
return UrlComponent.urlArray;
}
}
並使用它:
<div>
url works! {{staticUrlArray}}
</div>
為了避免 Angular 在每個周期調用 get staticUrlArray,您可以在組件的公共范圍內保存一個類引用:
export class UrlComponent {
static urlArray;
public classReference = UrlComponent;
constructor() {
UrlComponent.urlArray = "Inside Contructor";
}
}
然后就可以直接使用了:
<div>
url works! {{ classReference.urlArray }}
</div>
您也可以只聲明類類型的字段,如下所示:
export class UrlComponent {
static urlArray;
UrlComponent = UrlComponent;
constructor() {
UrlComponent.urlArray=" Inside Contructor"
}
}
然后,您可以使用此前綴引用靜態變量:
<div>
url works! {{UrlComponent.urlArray}}
</div>
這也適用/對於直接在模板中引用枚舉之類的東西或控制台之類的對象是必要的。
有趣的是,在模板中使用以“readonly”為前綴的類屬性確實有效。 因此,如果您的靜態變量實際上是一個常量,請繼續使用
export class UrlComponent {
readonly urlArray;
}
無需在構造函數中編碼的解決方案:
export class UrlComponent {
readonly static urlArray = ' Inside Class';
readonly UrlArray = UrlComponent.urlArray;
constructor() { }
}
您可以在其他組件或類中使用該靜態字段:
import {UrlComponent} from 'some-path';
export class UrlComponent2 {
readonly UrlArray = UrlComponent.urlArray;
}
在模板中使用(注意UrlArray
大寫“U”):
<div>
url works!
{{UrlArray}}
</div>
這對我有用,但驗證器的錯誤消息停止工作
這是我的代碼。
<form [formGroup]="staticformGroup" class="form">
<div class="box">
<input type="text" id="uname" class="field" formControlName="name">
<span class="PlaceHolder" id="namePlaceHolder">Name</span>
<small *ngIf="name.invalid && name.touched" class="text-danger">Name is Required</small>
</div>
<div class="box">
<input type="mailOrNum" id="mailOrNum" class="field" formControlName="email">
<span class="PlaceHolder" id="mailPlaceHolder">Email</span>
<small *ngIf="email.invalid && email.touched" class="text-danger">invalid value</small>
</div>
</form>
.ts 文件:
static signup = new FormGroup({
'name': new FormControl("", Validators.required),
'email': new FormControl("", [Validators.required, Validators.email])
});
get staticformGroup():FormGroup{
return SignUpFormComponent.signup;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.