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

后端 未结 11 1423
借酒劲吻你
借酒劲吻你 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:38

    I needed to do the same thing and maybe this is what you wanted.
    More DRY and it can be used with module too.

    export enum Role {
        ServiceAdmin, CompanyAdmin, Foreman, AgentForeman, 
        CrewMember, AgentCrewMember, Customer
    }
    
    export namespace Role {
    
      export function keys(): Array{
        var keys = Object.keys(Role);
        return keys.slice(keys.length / 2, keys.length-1);
      }
    }
    

    the object output before the slice

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

    typescript merges the two declarations hence the keys.lenght-1

    and the ngFor:

    {{ role }}

    more info:
    Typescript's Declaration merging

    based on:
    TypeScript: Add functions to an Enum https://basarat.gitbooks.io/typescript/content/docs/enums.html (at the end of the enums chapter.)

提交回复
热议问题