Select based on enum in Angular2

前端 未结 11 2020
别那么骄傲
别那么骄傲 2020-11-28 23:26

I have this enum (I\'m using TypeScript) :

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

I would like to build a

相关标签:
11条回答
  • 2020-11-28 23:28

    This is the best option which you can apply without any pipes or extra code.

    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];
    
      }
    }
    
    0 讨论(0)
  • 2020-11-28 23:29

    Another similar solution, that does not omit "0" (like "Unset"). Using filter(Number) IMHO is not a good approach.

    @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
    }
    
    0 讨论(0)
  • 2020-11-28 23:37

    Here is a very straightforward way for Angular2 v2.0.0. For completeness sake, I have included an example of setting a default value of the country select via reactive forms.

    @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
      }
    }
    
    0 讨论(0)
  • 2020-11-28 23:39

    As of Angular 6.1 and above you can use the built-in KeyValuePipe like below (pasted from angular.io docs).

    I'm assuming that an enum contains human friendly readable strings of course :)

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

    0 讨论(0)
  • 2020-11-28 23:40

    Yet another Solution with 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);
    

    This will print:

    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"}
    
    0 讨论(0)
  • 2020-11-28 23:42
    export enum Unit
    {
        Kg = 1,
        Pack,
        Piece,
        Litre
    }
    

    //with 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 map = new Map<string, string>();
        keys.forEach(key => map.set(key, enumObj[key]))
        console.log( Array.from(map));
        return Array.from(map);
      }
    
    }
    

    //With set

        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);
          }
    
        }
    
    0 讨论(0)
提交回复
热议问题