Select based on enum in Angular2

One more solution if you don’t want to create a new pipe. You could also extract keys into helper property and use it:

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <select>
        <option *ngFor="let key of keys" [value]="key" [label]="countries[key]"></option>
      </select>
    </div>
  `,
  directives: []
})
export class App {

  countries = CountryCodeEnum

  constructor() {
    this.keys = Object.keys(this.countries).filter(k => !isNaN(Number(k)));
  }
}

Demo: http://plnkr.co/edit/CMFt6Zl7lLYgnHoKKa4E?p=preview

Edit:

if you need the options as numbers instead of strings:

  • replace [value] with [ngValue]
  • add .map(Number) after .filter(...)

Leave a Comment