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

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

    The scope of the template is the component instance. If you want to access something outside this scope you need to make it available from withing your component instance:

    This also works if the enum keys do not start with 0

    @Pipe({name: 'enumToArray'})
    export class EnumToArrayPipe implements PipeTransform {
      transform(value) : Object {
        return Object.keys(value).filter(e => !isNaN(+e)).map(o => { return {index: +o, name: value[o]}});
      }
    }
    
    @Component({
      ...
      imports: [EnumsToArrayPipe],
      template: `
    {{item.index}}: {{item.name}}
    ` }) class MyComponent { roles = Role; }

    See also https://stackoverflow.com/a/35750252/217408

提交回复
热议问题