[英]How to use an enum in an Angular Component
我的 Angular 組件往往具有全局狀態(或“模式”),因此我正在尋找一種有效編碼的方法。 我試圖做的是:
@Component({
....
})
export class AbcComponent implements OnInit {
enum State {
init, view, edit, create, wait
}
state: State = State.init;
其思想是AbcComponent 內部的函數可以簡單地通過設置state屬性來驅動模板的運行。 例如:
<div class="col" *ngIf="state === State.view"> ... </div>
問題是枚舉定義不能出現在類結構中。 然后,如果我將它移到類結構之外,那么模板就不會在其本地范圍內。
有沒有不同的方法來做到這一點?
PS 如果有任何興趣,我一直在做的是我有幾個布爾屬性,每個狀態一個。 例如modeInit modeView等。它可以工作,但它很笨拙,因為一次只能有一個為真。
您可以在類之外定義State
枚舉,可能在另一個文件中:
export enum State {
init,
view,
edit,
create,
wait
}
並將枚舉分配給類中的公共字段:
import { State } from "../models/app-enums.model";
@Component({
....
})
export class AbcComponent implements OnInit {
public StateEnum = State;
public state = State.init;
...
}
然后可以使用該公共字段來引用模板中的枚舉:
<div class="col" *ngIf="state === StateEnum.view"> ... </div>
您可以定義一個方法或 getter,並將當前狀態值與已導入的枚舉進行比較。 像這樣:
import { State } from "../models/state-enum.ts";
@Component({
....
})
export class AbcComponent implements OnInit {
private state: State = State.init;
...
get isView() {
return this.state === State.view;
}
}
模板.html
<div *ngIf="isView">Oh is view!</div>
您還可以使用聲明合並使枚舉作為組件的靜態成員可用。
@Component({
....
})
export class AbcComponent implements OnInit {
state = AbcComponent.State.init;
}
export namespace AbcComponent {
export enum State {
init, view, edit, create, wait
}
}
然后從constructor
字段在模板中訪問它
<div class="col" *ngIf="state === constructor.State.view"> ... </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.