3

I want to bind an enum as options in a HTML selector

    export enum MY_ENUM{
    ONE = 'One',
    TWO = 'Two',
    THREE = 'Three'
}

How do I bind this as options for my HTML select using ngFor

Rasula Caldera
  • 305
  • 1
  • 9

2 Answers2

1

I would use Object.values to get a list of the enum values like so:

this.options = Object.value(MY_ENUM);

And then in the template

<select>
  <option *ngFor="let option of options" [value]="option">{{option}}</option>
</select>
Teddy Sterne
  • 13,774
  • 2
  • 46
  • 51
  • As you can see the key and the value are different. So this doesnt work for me – Rasula Caldera Oct 09 '18 at 06:03
  • Your question didn't state which value you wanted to display and which one you wanted to use for the value so i assumed you wanted to use the string value for both. You could do `this.options = Object.entries(MY_ENUM).map(([key, value]) => ({key, value}))` or something else depending on your use case. – Teddy Sterne Oct 09 '18 at 13:59
0

You can do like this:

<select>
  <option *ngFor="let opt of opts"
  [value]="opt.id" >
  {{opt.name}}
  </option>
</select>

where opts is an array that you build from Enum

enum EnumExample {
  OPT1 = "opt1",
  OPT2 = "opt2"
}

export class Example {
  public opts: any[];
  constructor(){
    this.opts = [
      {id: "OPT1", name=EnumExample.OPT1},
      {id: "OPT2", name=EnumExample.OPT2}];

  }
}

I didnt find a way to do directly from Enum.

Guilherme Alencar
  • 1,243
  • 12
  • 21