Search code examples
angularenumsngfor

Iterate Enum in ngFor, Angular5


I am trying to iterate an enum in TypeScript to create radio buttons corresponding to them. I know how to do this using arrays but I am struggling to do it with enums.

enum labelModes{
'MultiClass',
'MultiLabel'
}
@Component({
    selector: 'app-label-type',
    template: `
    
    <div class="text-center p-2">
    Type of labeling:<br> 
       <div *ngFor = "let labelMode of labelModes">
            <input
                type = "radio"
                name = "labelType"
                value = "{{labelMode}}"
                (change) = "radioChangeHandler($event)"> {{labelMode}}
    </div>
  `
})

Nothing shows up


Solution

  • My code to iterate the enum. I had to set values for the elements and then access them using keys and objects. Ideally you should be able to do object.keys(labelModes) instead of keys(values). But this is the only way it worked for me.

    the values on the left in the enum are returned.

    export enum labelModes {
      multiclass = "multiclass",
      multilabel = "multilabel"
    }
    @Component({
      selector: "app-label-type",
      template: `
      
      <div class="text-center p-2">
        Type of labeling:<br> 
           <div *ngFor = "let labelMode of values">
                <input
                    type = "radio"
                    name = "labelType"
                    value = "{{labelMode}}"
                    (change) = "radioChangeHandler($event)"> {{labelMode}}
          </div>
        `
        })
    export class LabelType {
      ngOnInit() {}
      selectedLabelType: string = " ";
         
      values = Object.keys(labelModes);
    }