如何在Angular2 ngSwitch语句中使用typcript枚举值

前端之家收集整理的这篇文章主要介绍了如何在Angular2 ngSwitch语句中使用typcript枚举值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Typescript枚举似乎与Angular2的ngSwitch指令自然匹配。但是当我尝试在我的组件模板中使用枚举,我得到“无法读取属性’xxx’未定义在…”。如何在我的组件模板中使用枚举值

请注意,这不同于如何基于枚举的所有值创建html选择选项(ngFor)。这个问题是关于ngSwitch基于枚举的特定值。虽然同样的方法创建一个类的内部引用枚举出现。

您可以创建对组件类中的枚举的引用(我只是将初始字符更改为小写),然后使用模板( plunker)中的引用:
  1. import {Component} from 'angular2/core';
  2.  
  3. enum CellType {Text,Placeholder}
  4. class Cell {
  5. constructor(public text: string,public type: CellType) {}
  6. }
  7. @Component({
  8. selector: 'my-app',template: `
  9. <div [ngSwitch]="cell.type">
  10. <div *ngSwitchCase="cellType.Text">
  11. {{cell.text}}
  12. </div>
  13. <div *ngSwitchCase="cellType.Placeholder">
  14. Placeholder
  15. </div>
  16. </div>
  17. <button (click)="setType(cellType.Text)">Text</button>
  18. <button (click)="setType(cellType.Placeholder)">Placeholder</button>
  19. `,})
  20. export default class AppComponent {
  21.  
  22. // Store a reference to the enum
  23. cellType = CellType;
  24. public cell: Cell;
  25.  
  26. constructor() {
  27. this.cell = new Cell("Hello",CellType.Text)
  28. }
  29.  
  30. setType(type: CellType) {
  31. this.cell.type = type;
  32. }
  33. }

猜你在找的Angularjs相关文章