根据Angular2

时间:2016-03-02 14:30:58

标签: typescript angular angular2-forms

我有这个枚举(我正在使用 TypeScript ):

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

我想在表单中构建一个 select ,每个选项将枚举整数值作为值,以及枚举文本作为标签,像这样:

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

我该怎么做?

11 个答案:

答案 0 :(得分:45)

<强>更新

而不是pipes: [KeysPipe]

使用

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

<强>原始

使用https://stackoverflow.com/a/35536052/217408

中的keys管道

我不得不稍微修改一下管道,使其与枚举一起正常工作 (另见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) {
      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

另见How to use *ngFor with Object?

答案 1 :(得分:45)

如果您不想创建新管道,还有一个解决方案。您还可以将密钥提取到helper属性中并使用它:

@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(Number)
  }
}

演示: http://plnkr.co/edit/CMFt6Zl7lLYgnHoKKa4E?p=preview

答案 2 :(得分:19)

对于Angular2 v2.0.0,这是一种非常简单的方法。为了完整起见,我添加了一个通过reactive forms设置country选择默认值的示例。

@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 :(得分:7)

另一个类似的解决方案,不会忽略&#34; 0&#34; (例如&#34; Unset&#34;)。使用过滤器(数字)恕我直言不是一个好方法。

@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
}

答案 4 :(得分:6)

我更倾向于在我的Angular App中共享一个简单的实用程序函数,将enum转换为标准数组以构建选择:

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

用Component填充Component中的变量:

public countries = enumSelector(CountryCodeEnum);

然后将我的材质选择填充为我的旧数组:

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

感谢这个帖子!

答案 5 :(得分:3)

从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']]);
}

答案 6 :(得分:1)

使用字符串枚举,您可以尝试这一点。

我的字符串枚举具有以下定义:

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

并以下列方式转换为js:

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

我的项目中有一些这样的,所以在共享服务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;
       }
   }

在组件构造函数中初始化并将其绑定到您的模板,如下所示:

在组件中:

    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中的提供者数组中,以便您可以轻松地将其注入不同的组件中。

我是打字稿的新手,所以如果我错了或者有更好的解决方案,请纠正我。

答案 7 :(得分:1)

这个答案的另一个衍生,但这实际上将值映射为数字,而不是将它们转换为字符串,这是一个错误。它也适用于基于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));;
  }
}

答案 8 :(得分:0)

这是最好的选项,您可以应用它而无需任何管道或多余的代码。

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];

  }
}

答案 9 :(得分:0)

又一个解决方案,使用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"}

答案 10 :(得分:0)

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);
      }

    }