Carl G Carl G - 1 year ago 856
TypeScript Question

How to use a typescript enum value in an Angular2 ngSwitch statement

The Typescript enum seems a natural match with Angular2's ngSwitch directive. But when I try to use an enum in my component's template, I get "Cannot read property 'xxx' of undefined in ...". How can I use enum values in my component template?

Please note that this is different from how to create html select options based upon ALL of the values of an enum (ngFor). This question is about ngSwitch based upon a particular value of an enum. Although the same approach of creating an class-internal reference to the enum appears.

Answer Source

You can create a reference to the enum in your component class (I just changed the initial character to be lower-case) and then use that reference from the template (plunker):

import {Component} from 'angular2/core';

enum CellType {Text, Placeholder}
class Cell {
  constructor(public text: string, public type: CellType) {}
  selector: 'my-app',
  template: `
    <div [ngSwitch]="cell.type">
      <div *ngSwitchWhen="cellType.Text">
      <div *ngSwitchWhen="cellType.Placeholder">
    <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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download