Lichay Tiram
Lichay Tiram

Reputation: 293

I want to get dropdown with selected value that combine with enum

I am trying to achieve dropdown with first value selected and disable only to show to user. It should recognize enum instead regular string

HTML

            <select name="level" [(ngModel)]="level">
                <option disabled [selected]="disabledValue" [value]="disabledValue">{{disabledValue}}</option>
                <option *ngFor="let level of levelKeys" [value]="level">{{level}}</option>
            </select>

ts

  public disabledValue: string = 'level';
  public level: Level = Level.EMPTY; // Level is enum

enum

export enum Level {
    EMPTY, EASY, NORMAL, HARD
}

Level class contain easy normal and hard.

In my user interface he should see level and after click dropdown show him Level class with 3 options

Dropdown look like this ->

[level] selected + disabled 
[easy] option 1
[normal] option 2
[hard] option 3

Thank for your help guys :-)

Upvotes: 0

Views: 1292

Answers (1)

Ammar
Ammar

Reputation: 1314

well, using an enum is not really any different than using an array in that regard. I will not ask why must that be an enum, but to get the values from an enum you can do the following:

enum Level {
  EMPTY = 'level',
  EASY= 'EASY',
  NORMAL = 'NORMAL',
  HARD = 'HARD'
}

and then in your component.ts file:

levelKeys = Object.values(Level);

I have a working example here:
https://stackblitz.com/edit/angular-ivy-dcqawz?file=src/app/app.component.ts

and it looks like this:

template.html:

<select name="level" [(ngModel)]="level" >
    <option *ngFor="let level of levelKeys" [disabled]="level === 'level'" [value]="level">{{level}}</option>
</select>

component.ts

import { Component, VERSION } from '@angular/core';

enum Level {
  EMPTY = 'level',
  EASY= 'EASY',
  NORMAL = 'NORMAL',
  HARD = 'HARD'
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  public level: Level = Level.EMPTY; 
  levelKeys = Object.values(Level);
}

this will show a dropdown like this:

enter image description here

please have a look :-)

Upvotes: 2

Related Questions