How can I use ngFor to iterate over Typescript Enum as an array of strings

后端 未结 11 1424
借酒劲吻你
借酒劲吻你 2020-12-13 12:03

I am using Angular2 and Typscript. I have an enum:

export enum Role {
    ServiceAdmin, CompanyAdmin, Foreman, AgentForeman, 
    CrewMember, AgentCrewMembe         


        
相关标签:
11条回答
  • 2020-12-13 12:16

    You can just use the "keyvalue" pipe introduced in Angular 6.1.

    <p *ngFor="let enum of TestEnum | keyvalue">
      {{ enum.key }} - {{ enum.value}}
    </p>
    

    See here for a full example -> https://stackblitz.com/edit/angular-gujg2e

    0 讨论(0)
  • 2020-12-13 12:16

    ES6 supports

    export enum E {
        a = 'First',
        b = 'Second',
        c = 'Third'
    }
    
    let keyValueArray = Object.keys(E).map(k => ({key: k, value: E[k as any]}));
    
    0 讨论(0)
  • 2020-12-13 12:17
    export enum Priority {
      LL = 1,   // VERY LOW
      L = 2,    // LOW
      N = 3,    // NORMAL
      U = 4,    // HIGH
      UU = 5    // VERY HIGH
    }
    

    Your angular component.ts :

    import { Priority } from './../shared/core/config/datas.config';
    
    @Component({
      selector: 'app-yourcomponent',
      template: `
        <ng-container *ngFor="let p of getPriority">
           <div> {{p.key}} / {{p.value}} </div>
        </ng-container> 
      `
    })
    
    export class YourComponent {
      getPriority = this.getENUM(Priority);
    
      getENUM(ENUM:any): string[] {
        let myEnum = [];
        let objectEnum = Object.keys(ENUM);
        const values = objectEnum.slice( 0 , objectEnum.length / 2 );
        const keys = objectEnum.slice( objectEnum.length / 2 );
    
        for (let i = 0 ; i < objectEnum.length/2 ; i++ ) {
          myEnum.push( { key: keys[i], value: values[i] } ); 
        }
        return myEnum;
      }
    }
    
    0 讨论(0)
  • 2020-12-13 12:18

    I have the enum:

    export enum FileCategory {
      passport = 'Multipass',
      agreement = 'Personal agreement',
      contract = 'Contract',
      photo = 'Self photos',
      other = 'Other'
    }
    

    In the component ts file:

    export class MyBestComponent implements OnInit {
      fileCategory = FileCategory;
    
      // returns keys of enum
      fileKeys(): Array<string> {
        const keys = Object.keys(this.fileCategory);
        return keys;
      }
    
      // returns values of enum
      fileVals(): Array<string> {
        const keys = Object.keys(this.fileCategory);
        return keys.map(el => Object(this.fileCategory)[el]);
      }
    

    In the HTML template display these enum's values and keys:

      <a *ngFor="let cat of fileVals()"
         (click)="addFileCategory(cat)">{{cat}}</a>
      <a *ngFor="let cat of fileKeys()"
         (click)="addFileCategory(cat)">{{cat}}</a>
    
    0 讨论(0)
  • 2020-12-13 12:22

    using pipe:

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'enum'
    })
    export class EnumSelectPipe implements PipeTransform {
      transform(value: any): [number, string][] {
        return Object.keys(value).filter(t => isNaN(+t)).map(t => [value[t], t]);
      }
    }
    

    and in the template:

    <mat-select formControlName="type" placeholder="Package Type">
      <mat-option *ngFor="let pType of PackageTypes | enum" [value]="pType[0]">{{ pType[1] | title}}</mat-option>
    </mat-select>
    
    0 讨论(0)
  • 2020-12-13 12:24

    An enum is just an object.

    Your enum is written something like this in JavaScript:

    {
        0: "ServiceAdmin", 
        1: "CompanyAdmin", 
        2: "Foreman", 
        3: "AgentForeman", 
        4: "CrewMember", 
        5: "AgentCrewMember", 
        6: "Customer", 
        ServiceAdmin: 0, 
        CompanyAdmin: 1, 
        Foreman: 2, 
        AgentForeman: 3, 
        CrewMember: 4,
        AgentCrewMember: 5,
        Customer: 6
    }
    

    So you can iterate it this way (plnkr):

    @Component({
        ...
        template: `
        <div *ngFor="let item of keys()">
          {{ item }}
        </div>  
      `
    })
    export class YourComponent {
        role = Role;
        keys() : Array<string> {
            var keys = Object.keys(this.role);
            return keys.slice(keys.length / 2);
        }
    }
    

    Or would be better to create custom pipe:

    @Pipe({
      name: 'enumToArray'
    })
    export class EnumToArrayPipe implements PipeTransform {
      transform(data: Object) {
        const keys = Object.keys(data);
        return keys.slice(keys.length / 2);
      }
    }
    

    Example

    Update

    Typescript 2.4 allows enum members to contain string initializers like:

    enum Colors {
        Red = "RED",
        Green = "GREEN",
        Blue = "BLUE",
    }
    

    in this case you can just return Object.keys(data); from pipe.

    0 讨论(0)
提交回复
热议问题