本文介绍了选择基于枚举在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 :

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

我怎样才能做到这一点?

How can I do this ?

推荐答案

从的

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

我不得不修改管道位,使其与枚举​​正常工作
(见How没有一赠打字稿枚举条目的名称?)

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: `
  <select>
     <option *ngFor="#item of countries | keys" [value]="item.key">{{item.value}}</option>
  </select>
`
})
class MyComponent {
  countries = CountryCodeEnum;
}

这篇关于选择基于枚举在Angular2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 16:39