根据 Angular2 中的枚举进行选择 [英] Select based on enum in Angular2
本文介绍了根据 Angular2 中的枚举进行选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个枚举(我正在使用 TypeScript):
I have this enum (I'm using TypeScript) :
export enum CountryCodeEnum {
France = 1,
Belgium = 2
}
我想在我的表单中构建一个select,对于每个选项,将枚举整数值作为值,以及枚举文本作为标签,像这样:
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>
我该怎么做?
推荐答案
update2 通过创建数组简化
@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;
}
更新
代替管道:[KeysPipe]
使用
@NgModule({
declarations: [KeysPipe],
exports: [KeysPipe],
}
export class SharedModule{}
@NgModule({
...
imports: [SharedModule],
})
原创
使用 https://stackoverflow.com/a/35536052/217408 管道中的 keys
管道一个>
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;
}
这篇关于根据 Angular2 中的枚举进行选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文