如何在Angular2 ngSwitch语句中使用Typescript枚举值 [英] How to use a typescript enum value in an Angular2 ngSwitch statement
问题描述
Typescript枚举似乎与Angular2的ngSwitch指令自然匹配.但是,当我尝试在组件模板中使用枚举时,出现无法读取...中未定义的属性'xxx'".如何在组件模板中使用枚举值?
The Typescript enum seems a natural match with Angular2's ngSwitch directive. But when I try to use an enum in my component's template, I get "Cannot read property 'xxx' of undefined in ...". How can I use enum values in my component template?
请注意,这与基于枚举(ngFor)的所有值创建html select选项的方式不同.这个问题是关于基于enum的特定值的ngSwitch的.尽管出现了创建对枚举的类内部引用的相同方法.
Please note that this is different from how to create html select options based upon ALL of the values of an enum (ngFor). This question is about ngSwitch based upon a particular value of an enum. Although the same approach of creating an class-internal reference to the enum appears.
推荐答案
您可以在组件类中创建对枚举的引用(我只是将初始字符更改为小写),然后从模板中使用该引用( plunker ):
You can create a reference to the enum in your component class (I just changed the initial character to be lower-case) and then use that reference from the template (plunker):
import {Component} from 'angular2/core';
enum CellType {Text, Placeholder}
class Cell {
constructor(public text: string, public type: CellType) {}
}
@Component({
selector: 'my-app',
template: `
<div [ngSwitch]="cell.type">
<div *ngSwitchCase="cellType.Text">
{{cell.text}}
</div>
<div *ngSwitchCase="cellType.Placeholder">
Placeholder
</div>
</div>
<button (click)="setType(cellType.Text)">Text</button>
<button (click)="setType(cellType.Placeholder)">Placeholder</button>
`,
})
export default class AppComponent {
// Store a reference to the enum
cellType = CellType;
public cell: Cell;
constructor() {
this.cell = new Cell("Hello", CellType.Text)
}
setType(type: CellType) {
this.cell.type = type;
}
}
这篇关于如何在Angular2 ngSwitch语句中使用Typescript枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!