如何在Angular2 ngSwitch语句中使用typcript枚举值
发布时间:2020-12-17 08:29:51 所属栏目:安全 来源:网络整理
导读:Typescript枚举似乎与Angular2的ngSwitch指令自然匹配。但是当我尝试在我的组件模板中使用枚举,我得到“无法读取属性’xxx’未定义在…”。如何在我的组件模板中使用枚举值? 请注意,这不同于如何基于枚举的所有值创建html选择选项(ngFor)。这个问题是关于
Typescript枚举似乎与Angular2的ngSwitch指令自然匹配。但是当我尝试在我的组件模板中使用枚举,我得到“无法读取属性’xxx’未定义在…”。如何在我的组件模板中使用枚举值?
请注意,这不同于如何基于枚举的所有值创建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; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |