如何在Angular2的ngSwitch语句中使用typescript枚举值
如何在Angular2的ngSwitch语句中使用typescript枚举值
在Angular2的ngSwitch指令中,TypeScript枚举似乎是一个很自然的匹配。但是当我尝试在组件模板中使用枚举时,我得到了“Cannot read property \'xxx\' of undefined in ...” 的错误。我该如何在组件模板中使用枚举值?
请注意,这与基于枚举的所有值创建HTML选择选项的方法(ngFor)不同。这个问题是关于基于枚举特定值的ngSwitch的。虽然创建一个类内部的枚举引用的方法是相同的。
admin 更改状态以发布 2023年5月24日
你可以在组件类中创建对枚举的引用(我只是更改了初始字符使其为小写),然后从模板(plunker)中使用该引用:
import {Component} from 'angular2/core'; enum CellType {Text, Placeholder} class Cell { constructor(public text: string, public type: CellType) {} } @Component({ selector: 'my-app', template: ` {{cell.text}} Placeholder `, }) 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; } }