@H_
502_0@
Typescript枚举似乎与Angular2的ngSwitch指令自然匹配。但是当我尝试在我的组件模板中使用枚举,我得到“无法读取
属性’xxx’未定义在…”。如何在我的组件模板中使用
枚举值?
@H_
301_1@请注意,这不同于如何基于枚举的所有值创建html选择选项(ngFor)。这个问题是关于ngSwitch基于枚举的特定值。虽然同样的
方法创建一个类的内部引用枚举出现。
您可以创建对组件类中的枚举的引用(我只是将初始字符更改为小写),然后使用模板(
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;
}
}