Iterate Over an Enum In Angular

Iterate over a TypeScript enum and use the values to populate a dropdown list.

Namespace

We use a TypeScript namespace to add the values() method to the PhoneType enum.

phone-type.ts
export enum PhoneType {
  Mobile = 0,
  Home,
  Work
}

export namespace PhoneType {

  export function values() {
    return Object.keys(PhoneType).filter(
      (type) => isNaN(<any>type) && type !== 'values'
    );
  }
}

The Object.keys(PhoneType) method used above returns this array:

Array(7)
  0: "0"
  1: "1"
  2: "2"
  3: "Mobile"
  4: "Home"
  5: "Work"
  6: "values"

The filter function removes the numeric values and the value method.

Template

To access the enum values in a template we declare the enum on our component class and use the values method in an *ngFor loop.

enum-iterator.component.ts
import { Component } from '@angular/core';
import { PhoneType } from './phone-type';

@Component({
  selector: 'app-enum-iterator',
  template: `
    <p>
      <select name="phoneType">
        <option *ngFor="let type of PhoneType.values();">
          {{type}}
        </option>
      </select>
    </p>
  `
})
export class EnumIteratorComponent {

  PhoneType = PhoneType;

}

This is the result.