0

我看过这样的问题。但这并不能完全回答我的问题。我想将局部变量名称绑定到枚举的值,如以下(高度简化)示例:

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
    ...
}

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>

编辑: 我认为解决方案在以下答案中:How to use a typescript enum value in an Angular2 ngSwitch statement。你们有什么感想?

4

2 回答 2

2

这就是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>

对于可能将键用作字符串的情况,枚举不是最佳选择,因为它们需要额外的查找并且不允许严格键入。正如这里所解释的,普通对象通常是更宽松的类型的更好选择,命名空间更适合更严格的类型。

于 2017-09-11T09:54:11.700 回答
0
public certainStates: typeof CertainState = CertainState;

应该

public certainStates: any = CertainState;

或者

public certainStates: {[s: number]: string } = CertainState;
于 2017-09-11T07:55:29.363 回答