[英]Use a TypeScript enum as an Angular template variable name with ngTemplateOutlet
I have looked at questions like this one . 我看过这样的问题这一个 。 But it doesn't quite answer my question.
但这并不能完全回答我的问题。 I want to bind the local variable name to the enum's value like in the following (heavily simplified) example:
我想将局部变量名称绑定到枚举的值,如下面的示例(简化)所示:
In certain-state.component.ts
: 在
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
: 在
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>
EDIT: I think the solution is in the following answer: How to use a typescript enum value in an Angular2 ngSwitch statement . 编辑:我认为解决方案在以下答案中: 如何在Angular2 ngSwitch语句中使用打字稿枚举值 。 What do you guys think?
你们有什么感想?
This is what CertainState
enum really is: 这就是
CertainState
枚举的真正CertainState
是:
(function (CertainState) {
CertainState[CertainState["VALID"] = 0] = "VALID";
CertainState[CertainState["INVALID"] = 1] = "INVALID";
})(CertainState = exports.CertainState || (exports.CertainState = {}));
It basically maps keys to indexes and vice versa. 它基本上将键映射到索引,反之亦然。
So it should be typed like: 因此,应将其键入为:
public state: number;
public certainStates: typeof CertainState = CertainState;
And if state name is supposed to be used, it can be looked up on enum: 如果应该使用州名,则可以在枚举中查找它:
<ng-container *ngTemplateOutlet="state_{{certainStates[state]}}"></ng-container>
<ng-template #state_{{certainStates[certainStates.VALID]}}><span>VALID</span></ng-template>
Or enum index can be used directly: 或枚举索引可以直接使用:
<ng-container *ngTemplateOutlet="state_{{state}}"></ng-container>
<ng-template #state_{{certainStates.VALID}}><span>VALID</span></ng-template>
Enums aren't the best choice for cases where a key may be used as a string, because they require extra lookup and don't allow strict typing. 对于可能将键用作字符串的情况,枚举不是最佳选择,因为枚举需要额外的查找并且不允许严格的键入。 As explained here , plain object is generally a better choice for looser typing, and a namespace is good for stricter typing.
正如解释在这里 ,普通的对象一般是宽松的打字更好的选择,并命名空间有利于严格打字。
public certainStates: typeof CertainState = CertainState;
should be 应该
public certainStates: any = CertainState;
or 要么
public certainStates: {[s: number]: string } = CertainState;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.