Select 基于 Angular2 中的枚举
Select based on enum in Angular2
我有这个枚举(我正在使用 TypeScript):
export enum CountryCodeEnum {
France = 1,
Belgium = 2
}
我想在我的表单中构建一个select,每个选项 枚举整数值作为值,枚举文本作为标签,像这样:
<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;
}
更新
而不是pipes: [KeysPipe]
使用
@NgModule({
declarations: [KeysPipe],
exports: [KeysPipe],
}
export class SharedModule{}
@NgModule({
...
imports: [SharedModule],
})
原
使用来自
的 keys
管道
我不得不稍微修改管道以使其与枚举一起正常工作
(另见 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;
}
另见
如果您不想创建新管道,还有一个解决方案。您还可以将密钥提取到助手 属性 中并使用它:
@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)));
}
}
演示: http://plnkr.co/edit/CMFt6Zl7lLYgnHoKKa4E?p=preview
编辑:
如果您需要数字而不是字符串的选项:
- 将
[value]
替换为[ngValue]
- 在
.filter(...)
之后添加.map(Number)
这是 Angular2 v2.0.0 的一种非常简单的方法。为了完整起见,我提供了一个通过 reactive forms.
设置 country
select 默认值的示例
@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
}
}
我更喜欢在我的 Angular 应用程序中共享一个简单的实用函数,以将 enum
转换为标准数组以构建选择:
export function enumSelector(definition) {
return Object.keys(definition)
.map(key => ({ value: definition[key], title: key }));
}
用以下内容填充组件中的变量:
public countries = enumSelector(CountryCodeEnum);
然后填充我的 Material Select 作为我的旧数组:
<md-select placeholder="Country" [(ngModel)]="country" name="country">
<md-option *ngFor="let c of countries" [value]="c.value">
{{ c.title }}
</md-option>
</md-select>
感谢您的关注!
另一个类似的解决方案,不省略“0”(如"Unset")。使用 filter(Number) 恕我直言不是一个好方法。
@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
}
使用字符串枚举,您可以试试这个。
我的字符串枚举定义如下:
enum StatusEnum {
Published = <any> 'published',
Draft = <any> 'draft'
}
并按以下方式转换为js:
{
Published: "published",
published: "Published",
Draft: "draft",
draft: "Draft"
}
我的项目中有一些,因此在共享服务库中创建了小辅助函数:
@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;
}
}
在您的组件构造函数中初始化并将其绑定到您的模板,如下所示:
在组件中:
statusSelect;
constructor(private utils: UtilsService) {
this.statusSelect = this.utils.stringEnumToKeyValue(StatusEnum);
}
在模板中:
<option *ngFor="let status of statusSelect" [value]="status.value">
{{status.key}}
</option>
不要忘记将 UtilsService 添加到 app.module.ts 中的提供程序数组,这样您就可以轻松地将它注入不同的组件。
我是一个打字新手,如果我说错了或者有更好的解决方案,请指正。
这个答案的另一个分支,但这实际上将值映射为数字,而不是将它们转换为字符串,这是一个错误。它也适用于基于 0 的枚举
@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));;
}
}
从 Angular 6.1 及更高版本开始,您可以使用内置的 KeyValuePipe
,如下所示(从 angular.io 文档粘贴)。
我假设枚举当然包含人类友好的可读字符串:)
@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']]);
}
这是您无需任何管道或额外代码即可应用的最佳选项。
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];
}
}
另一个解决方案 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);
这将打印:
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"}
export enum Unit
{
Kg = 1,
Pack,
Piece,
Litre
}
//带地图
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);
}
}
//设置
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);
}
}
我有这个枚举(我正在使用 TypeScript):
export enum CountryCodeEnum {
France = 1,
Belgium = 2
}
我想在我的表单中构建一个select,每个选项 枚举整数值作为值,枚举文本作为标签,像这样:
<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;
}
更新
而不是pipes: [KeysPipe]
使用
@NgModule({
declarations: [KeysPipe],
exports: [KeysPipe],
}
export class SharedModule{}
@NgModule({
...
imports: [SharedModule],
})
原
使用来自
keys
管道
我不得不稍微修改管道以使其与枚举一起正常工作 (另见 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;
}
另见
如果您不想创建新管道,还有一个解决方案。您还可以将密钥提取到助手 属性 中并使用它:
@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)));
}
}
演示: http://plnkr.co/edit/CMFt6Zl7lLYgnHoKKa4E?p=preview
编辑:
如果您需要数字而不是字符串的选项:
- 将
[value]
替换为[ngValue]
- 在
.filter(...)
之后添加
.map(Number)
这是 Angular2 v2.0.0 的一种非常简单的方法。为了完整起见,我提供了一个通过 reactive forms.
设置country
select 默认值的示例
@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
}
}
我更喜欢在我的 Angular 应用程序中共享一个简单的实用函数,以将 enum
转换为标准数组以构建选择:
export function enumSelector(definition) {
return Object.keys(definition)
.map(key => ({ value: definition[key], title: key }));
}
用以下内容填充组件中的变量:
public countries = enumSelector(CountryCodeEnum);
然后填充我的 Material Select 作为我的旧数组:
<md-select placeholder="Country" [(ngModel)]="country" name="country">
<md-option *ngFor="let c of countries" [value]="c.value">
{{ c.title }}
</md-option>
</md-select>
感谢您的关注!
另一个类似的解决方案,不省略“0”(如"Unset")。使用 filter(Number) 恕我直言不是一个好方法。
@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
}
使用字符串枚举,您可以试试这个。
我的字符串枚举定义如下:
enum StatusEnum {
Published = <any> 'published',
Draft = <any> 'draft'
}
并按以下方式转换为js:
{
Published: "published",
published: "Published",
Draft: "draft",
draft: "Draft"
}
我的项目中有一些,因此在共享服务库中创建了小辅助函数:
@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;
}
}
在您的组件构造函数中初始化并将其绑定到您的模板,如下所示:
在组件中:
statusSelect;
constructor(private utils: UtilsService) {
this.statusSelect = this.utils.stringEnumToKeyValue(StatusEnum);
}
在模板中:
<option *ngFor="let status of statusSelect" [value]="status.value">
{{status.key}}
</option>
不要忘记将 UtilsService 添加到 app.module.ts 中的提供程序数组,这样您就可以轻松地将它注入不同的组件。
我是一个打字新手,如果我说错了或者有更好的解决方案,请指正。
这个答案的另一个分支,但这实际上将值映射为数字,而不是将它们转换为字符串,这是一个错误。它也适用于基于 0 的枚举
@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));;
}
}
从 Angular 6.1 及更高版本开始,您可以使用内置的 KeyValuePipe
,如下所示(从 angular.io 文档粘贴)。
我假设枚举当然包含人类友好的可读字符串:)
@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']]);
}
这是您无需任何管道或额外代码即可应用的最佳选项。
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];
}
}
另一个解决方案 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);
这将打印:
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"}
export enum Unit
{
Kg = 1,
Pack,
Piece,
Litre
}
//带地图
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);
}
}
//设置
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);
}
}