94

I have this enum (I'm using TypeScript) :

export enum CountryCodeEnum {
    France = 1,
    Belgium = 2
}

I would like to build a select in my form, with for each option the enum integer value as value, and the enum text as label, like this :

<select>
     <option value="1">France</option>
     <option value="2">Belgium</option>
</select>

How can I do this ?

11 Answers 11

75

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(...)
4
  • 1
    I didn't see the label in the dropdown, so I changed the option line to: <option *ngFor="#key of keys" [value]="key">{{countries[key]}}</option> Commented May 29, 2016 at 6:12
  • 25
    If your enum starts with 0 it will not work. It's better to use : Object.keys(CountryCodeEnum).filter(k => !isNaN(Number(k)));
    – Oleg
    Commented Dec 24, 2016 at 11:26
  • 1
    If you enum starts with 0, this is bad approach. If Object.keys(this.countries) returns ["0", "1", "2", "NotSet", "EU", "US"], the filter wil omit "0", so the filtered result will be ["1", "2"]. Not ["0","1", "2"] as I would expect.
    – Tomino
    Commented Sep 5, 2017 at 8:49
  • 1
    In addition to @Oleg's modification, I suggest appending .map(Number) to get a number[] back. This is to avoid any issues around binding a property to the key and expecting a number (rather than a string) back in your component. Commented Nov 16, 2017 at 17:08
73

update2 simplified by creating an array

@Pipe({name: 'enumToArray'})
export class EnumToArrayPipe implements PipeTransform {
  transform(value) : Object {
    return Object.keys(value).filter(e => !isNaN(+e)).map(o => { return {index: +o, name: value[o]}});
  }
}

@Component({
  ...
  imports: [EnumsToArrayPipe],
  template: `<div *ngFor="let item of roles | enumToArray">{{item.index}}: {{item.name}}</div>`
})
class MyComponent {
  roles = Role;
}

update

instead of pipes: [KeysPipe]

use

@NgModule({
  declarations: [KeysPipe],
  exports: [KeysPipe],
}
export class SharedModule{}
@NgModule({
  ...
  imports: [SharedModule],
})

original

Using the keys pipe from https://stackoverflow.com/a/35536052/217408

I had to modify the pipe a bit to make it work properly with enums (see also How to get names of enum entries?)

@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
  transform(value, args:string[]) : any {
    let keys = [];
    for (var enumMember in value) {
      if (!isNaN(parseInt(enumMember, 10))) {
        keys.push({key: enumMember, value: value[enumMember]});
        // Uncomment if you want log
        // console.log("enum member: ", value[enumMember]);
      } 
    }
    return keys;
  }
}

@Component({ ...
  pipes: [KeysPipe],
  template: `
  <select>
     <option *ngFor="let item of countries | keys" [value]="item.key">{{item.value}}</option>
  </select>
`
})
class MyComponent {
  countries = CountryCodeEnum;
}

Plunker

See also How to iterate object keys using *ngFor?

5
  • 2
    I will add one more change in order binding to work keys.push({ key: parseInt(enumMember, 10), value: value[enumMember] });
    – Mihail
    Commented Jun 23, 2017 at 13:13
  • @Component({ imports:; EnumToArrayPipe != EnumToArrayPipes ;-) Commented Jan 22, 2020 at 23:04
  • Not sure if this still works. You get undefined object.
    – Mukus
    Commented Nov 18, 2020 at 23:04
  • I get an error when I'm going to import EnumToArrayPipe in my component: 'imports' does not exist in type 'Component'. Commented Apr 12, 2022 at 8:17
  • @user3748973 please create a new question with all the information that allows to reproduct (Stackblitz example, ...) Commented Apr 12, 2022 at 13:07
22

Here is a very straightforward way for Angular2 v2.0.0. For completeness sake, I have included an example of setting a default value of the country select via reactive forms.

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

  constructor(private fb: FormBuilder) {
    this.keys = Object.keys(this.countries).filter(Number);
    this.country = CountryCodeEnum.Belgium; //Default the value
  }
}
3
  • You need to filter half of the values out as dfsq suggested: Object.keys(this.countries).filter(Number); Commented Nov 9, 2016 at 13:05
  • 1
    If you enum starts with 0, this is bad approach. If Object.keys(this.countries) returns ["0", "1", "2", "NotSet", "EU", "US"], the filter wil omit "0", so the filtered result will be ["1", "2"]. Not ["0","1", "2"] as I would expect.
    – Tomino
    Commented Sep 5, 2017 at 8:48
  • People seem to be forgetting to map the values back to number before using them for the correct answer check below
    – johnny 5
    Commented Apr 11, 2018 at 11:00
15

I've preferred to have a simple utility function shared across my Angular App, to convert the enum into a standard array to build selects:

export function enumSelector(definition) {
  return Object.keys(definition)
    .map(key => ({ value: definition[key], title: key }));
}

to fill a variable in the Component with:

public countries = enumSelector(CountryCodeEnum);

and then fill my Material Select as my old array based ones:

<md-select placeholder="Country" [(ngModel)]="country" name="country">
  <md-option *ngFor="let c of countries" [value]="c.value">
    {{ c.title }}
  </md-option>
</md-select>

Thanks for this thread!

9
  • What does your CountryCodeEnum look like?
    – phhbr
    Commented Aug 23, 2017 at 12:26
  • @phhbr I think I used non numeric values, like: export enum CountryCodeEnum { France = '1', Belgium = '2' } Commented Aug 23, 2017 at 15:49
  • The object of CountryCodeEnum looks something like this when using your enum: [ 1:"France", 2:"Belgium", France:1, Undefined:2, ]
    – phhbr
    Commented Aug 24, 2017 at 8:16
  • The problem with functions is that they run each time the change detection runs. A pipe would not run again if the input (CountryCodeEnum) didnt change.
    – Mick
    Commented Feb 7, 2021 at 16:45
  • @Mick if your selector depends on a input, yeah, you need a pipe :) Commented Feb 7, 2021 at 16:49
10

Another similar solution, that does not omit "0" (like "Unset"). Using filter(Number) IMHO is not a good approach.

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

export class App {
  countries = CountryCodeEnum;

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

// ** NOTE: This enum contains 0 index **
export enum CountryCodeEnum {
   Unset = 0,
   US = 1,
   EU = 2
}
2
  • 1
    Thanks a lot! this helped
    – Bellash
    Commented Jan 12, 2018 at 9:49
  • 1
    You need to defined keys: string[] = [];
    – Mick
    Commented Feb 7, 2021 at 16:53
5

Another spin off of this answer, but this actually maps the values as numbers, instead of converting them to strings which is a bug. It also works with 0 based enums

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

export class App {
  countries = CountryCodeEnum;

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

As of Angular 6.1 and above you can use the built-in KeyValuePipe like below (pasted from angular.io docs).

I'm assuming that an enum contains human friendly readable strings of course :)

@Component({
  selector: 'keyvalue-pipe',
  template: `<span>
    <p>Object</p>
    <div *ngFor="let item of object | keyvalue">
      {{item.key}}:{{item.value}}
    </div>
    <p>Map</p>
    <div *ngFor="let item of map | keyvalue">
      {{item.key}}:{{item.value}}
    </div>
  </span>`
})
export class KeyValuePipeComponent {
  object: {[key: number]: string} = {2: 'foo', 1: 'bar'};
  map = new Map([[2, 'foo'], [1, 'bar']]);
}

1
  • 1
    Yeah thats nice for object's and map's but the author asked for enum's and it will not work with an enum.
    – Mick
    Commented Feb 7, 2021 at 16:46
1

With string enums you can try this.

My string enum has the following definition:

    enum StatusEnum {
        Published = <any> 'published',
        Draft = <any> 'draft'
    }

and translates to js in the following way:

   {
       Published: "published", 
       published: "Published", 
       Draft: "draft", 
       draft: "Draft"
   }

I have a few of these in my project so created small helper function in a shared service lib:

   @Injectable()
   export class UtilsService {
       stringEnumToKeyValue(stringEnum) {
           const keyValue = [];
           const keys = Object.keys(stringEnum).filter((value, index) => {
               return !(index % 2);
           });

           for (const k of keys) {
               keyValue.push({key: k, value: stringEnum[k]});
           }

           return keyValue;
       }
   }

Init in your component constructor and Bind it to your template like this:

In component:

    statusSelect;

    constructor(private utils: UtilsService) {
        this.statusSelect = this.utils.stringEnumToKeyValue(StatusEnum);
    }

In template:

    <option *ngFor="let status of statusSelect" [value]="status.value">
        {{status.key}}
    </option>

Don't forget to add the UtilsService to the provider array in your app.module.ts so you can easily inject it in different components.

I'm a typescript newbie so please correct me if I'm wrong or if there are better solutions.

1
  • I had to remove the filter on even/odd indexes for mine to work Commented Nov 14, 2018 at 17:37
0

This is the best option which you can apply without any pipes or extra code.

import { Component } from '@angular/core';

 enum AgentStatus {
    available =1 ,
    busy = 2,
    away = 3,
    offline = 0
}


@Component({
  selector: 'my-app',
  template: `
  <h1>Choose Value</h1>

  <select (change)="parseValue($event.target.value)">
    <option>--select--</option>
    <option *ngFor="let name of options"
        [value]="name">{{name}}</option>
  </select>

  <h1 [hidden]="myValue == null">
    You entered {{AgentStatus[myValue]}}

  </h1>`
})
export class AppComponent { 


  options : string[];
  myValue: AgentStatus;
  AgentStatus : typeof AgentStatus = AgentStatus;

  ngOnInit() {
    var x = AgentStatus;
    var options = Object.keys(AgentStatus);
    this.options = options.slice(options.length / 2);
  }

  parseValue(value : string) {
    this.myValue = AgentStatus[value];

  }
}
0
export enum Unit
{
    Kg = 1,
    Pack,
    Piece,
    Litre
}

//with map

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'enumToArray'
})
export class EnumToArrayPipe implements PipeTransform {

  transform(enumObj: Object) {

    const keys = Object.keys(enumObj).filter(key => parseInt(key));
    let map = new Map<string, string>();
    keys.forEach(key => map.set(key, enumObj[key]))
    console.log( Array.from(map));
    return Array.from(map);
  }

}

//With set

    import { Pipe, PipeTransform } from '@angular/core';

    @Pipe({
      name: 'enumToArray'
    })
    export class EnumToArrayPipe implements PipeTransform {

      transform(enumObj: Object) {

        const keys = Object.keys(enumObj).filter(key => parseInt(key));
        let set = new Set();
        keys.forEach(key => set.add({ key: parseInt(key), value: enumObj[key] }))
        return Array.from(set);
      }

    }
-1

Yet another Solution with Angular 6.1.10 / Typescript ...

 enum Test {
   No,
   Pipe,
   Needed,
   Just,
   Use,
   Filter
 }

 console.log('Labels: ');
 let i = 0;
 const selectOptions = [
    ];
 Object.keys(Test).filter(key => !Number(key) && key !== '0').forEach(key => {
    selectOptions.push({position: i, text: key});
    i++;
  });
 console.log(selectOptions);

This will print:

Console:
Labels: 
    (6) [{…}, {…}, {…}, {…}, {…}, {…}]
    0: {position: 0, text: "No"}
    1: {position: 1, text: "Pipe"}
    2: {position: 2, text: "Needed"}
    3: {position: 3, text: "Just"}
    4: {position: 4, text: "Use"}
    5: {position: 5, text: "Filter"}

Not the answer you're looking for? Browse other questions tagged or ask your own question.