Home > Blockchain >  Select options from enum Angular
Select options from enum Angular

Time:12-31

I have this enum:

export enum LogLevel {
    DEBUG = 'DEBUG',
    INFO = 'INFO',
    WARNING = 'WARNING',
    ERROR = 'ERROR'
}

I would like to build a select in my form, with for each option the enum text as label:

<select>
     <option value="DEBUG">DEBUG</option>
     <option value="INFO">INFO</option>
     <option value="INFO">INFO</option>
     <option value="INFO">INFO</option>
</select>

What is a correct way of doing this?

CodePudding user response:

Try using Object.values to convert the enum to an array:

    <select>
      <option *ngFor="let logValue of Object.values(LogLevel)" [ngValue]="logValue">{{}logValue}</option>
   </select>

CodePudding user response:

here is a simple solution


 1. content of app.component.ts:

export class AppComponent {
  keys = Object.keys;
  logLevel = LogLevel;

  selected = LogLevel.DEBUG;

  select(event: any) {
    const value = event.target.value;
    this.selected = value;
    console.log(this.selected);
  }
}

export enum LogLevel {
  DEBUG = 'DEBUG',
  INFO = 'INFO',
  WARNING = 'WARNING',
  ERROR = 'ERROR',
}

 2. content of app.component.html

<select [(ngModel)]="selected" (change)="select($event)">
  <option *ngFor="let log of keys(logLevel)" [value]="logLevel[log]">
    {{ log }}
  </option>
</select>

for more infos check this link https://stackblitz.com/edit/angular-ivy-cuhnbw

  • Related