如何在 Angular2 ngSwitch 语句中使用打字稿枚举值

新手上路,请多包涵

Typescript 枚举似乎与 Angular2 的 ngSwitch 指令自然匹配。但是当我尝试在我的组件模板中使用枚举时,我得到“无法读取…中未定义的属性’xxx’”。如何在组件模板中使用枚举值?

请注意,这与如何根据枚举 (ngFor) 的所有值创建 html 选择选项不同。这个问题是关于 ngSwitch 基于枚举的特定值。尽管出现了创建对枚举的类内部引用的相同方法。

原文由 Carl G 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 516
2 个回答

您可以在组件类中创建对枚举的引用(我只是将初始字符更改为小写),然后使用模板中的该引用( 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;
  }
}

原文由 Carl G 发布,翻译遵循 CC BY-SA 3.0 许可协议

您现在可以这样做:

例如,枚举是:

 export enum MessagePriority {
    REGULAR= 1,
    WARNING,
    IMPORTANT,
}

一条状态消息,如下所示:

 export default class StatusMessage{
    message: string;
    priority: MessagePriority;

    constructor(message: string, priority: MessagePriority){
        this.message = message;
        this.priority = priority;
    }
}

然后在组件的 .ts 文件中,您可以执行以下操作:

     import StatusMessage from '../../src/entities/building/ranch/administration/statusMessage';
    import { MessagePriority } from '../../enums/message-priority';

    export class InfoCardComponent implements OnInit {
     messagePriority: typeof MessagePriority;

     constructor() {
     this.messagePriority = MessagePriority;
    }

    @Input() statusMessage: StatusMessage;
    ngOnInit(): void {}
}

最后组件的 HTML 如下所示:

 <div class="info-card" [ngSwitch]="statusMessage.priority">
    <h2 *ngSwitchCase="this.messagePriority.REGULAR" class="info-card__regular-message">{{statusMessage.message}}</h2>
    <h2 *ngSwitchCase="this.messagePriority.WARNING" class="info-card__warning-message">{{statusMessage.message}}</h2>
    <h2 *ngSwitchCase="this.messagePriority.IMPORTANT" class="info-card__important-message">{{statusMessage.message}}</h2>
</div>

请注意,枚举首先以“typeof MessagePriority”类型声明给类,然后通过调用“this.messagePriority = MessagePriority”定义绑定到类

原文由 Ivan Jamandilovski 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进