我已经看了这样的问题。但这并没有回答我的问题。我想将本地变量名称绑定到枚举的值,如以下(大量简化)示例:
in certain-state.component.ts
:
export enum CertainState {
VALID,
INVALID
}
export class CertainStateComponent {
// holder for the current state
public state: CertainState;
// store the actual enum in the instance of the class so that
// it is available in the template
public certainStates: typeof CertainState = CertainState;
// below is the logic which sets the state
...
}
in certain-state.component.html
:
<ng-container *ngTemplateOutlet="state_{{state}}"></ng-container>
// obviously this is invalid syntax but I want to demonstrate my intention
<ng-template #state_{{certainStates.VALID}}><span>VALID</span></ng-template>
<ng-template #state_{{certainStates.INVALID}}><span>INVALID</span></ng-template>
编辑:我认为解决方案是在以下答案中:如何在Angular2 ngswitch语句中使用打字稿枚举值。你们怎么看?
这就是CertainState
枚举的确是:
(function (CertainState) {
CertainState[CertainState["VALID"] = 0] = "VALID";
CertainState[CertainState["INVALID"] = 1] = "INVALID";
})(CertainState = exports.CertainState || (exports.CertainState = {}));
它基本上将键映射到索引,反之亦然。
因此,它应该像以下方式键入:
public state: number;
public certainStates: typeof CertainState = CertainState;
如果应该使用状态名称,则可以在枚举上查找:
<ng-container *ngTemplateOutlet="state_{{certainStates[state]}}"></ng-container>
<ng-template #state_{{certainStates[certainStates.VALID]}}><span>VALID</span></ng-template>
或枚举索引可以直接使用:
<ng-container *ngTemplateOutlet="state_{{state}}"></ng-container>
<ng-template #state_{{certainStates.VALID}}><span>VALID</span></ng-template>
枚举不是可以用作字符串的情况的最佳选择,因为它们需要额外的查找并且不允许严格的打字。如这里所述,普通对象通常是较松开打字的更好选择,并且名称空间非常适合更严格的打字。
public certainStates: typeof CertainState = CertainState;
应该是
public certainStates: any = CertainState;
或
public certainStates: {[s: number]: string } = CertainState;