Search code examples
angularangular2-template

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


I'm using Angular2 and TypeScript and I have an enum:

export enum Role {
    ServiceAdmin, CompanyAdmin, Foreman, AgentForeman, 
    CrewMember, AgentCrewMember, Customer
}

I want to use *ngFor to iterate over the enum. What is the best way to do this? Must I create a Pipe? Or is there a simpler way?


Solution

  • 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