Adrien Adrien - 1 year ago 455
TypeScript Question

Select based on enum in Angular2

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 :

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

How can I do this ?

Answer Source

Using the keys pipe from

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

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

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


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download