Search code examples
angularangular10angular11

How to show enum text values in Dropdown?


This is my enum values

export enum TaskCategory {
    Task = 0,
    Bug = 1,
}

html

                <div class="form-group">
                    <label class="col-form-label">Task Category <span class="text-danger">*</span></label>

                    <select class="select form-control" 
                        [class.invalid]="addTaskForm.get('taskcategory').invalid && addTaskForm.get('taskcategory').touched"
                        formControlName="taskcategory">
                        <option value="00000000-0000-0000-0000-000000000000">Select Task Category</option>
                        <option *ngFor="let state of states | keyvalue"  >{{state['value']}}</option>
                      

                    </select>
                    <div
                        *ngIf="addTaskForm.get('taskcategory').invalid && addTaskForm.get('taskcategory').touched">
                        <small
                            *ngIf="addTaskForm.get('taskcategory').invalid && addTaskForm.get('taskcategory').touched"
                            class="text-danger"> *Task Category is required</small>
                    </div>
                </div>

This the console Output.. Check this

I want only show the Enum text value ?

And how to get that selected option in backend ?


Solution

  • To use the enum in a template you can do:

    taskCategories: typeof TaskCategory = TaskCategory;
    

    For number enums you need to filter the numeric values out.

    categoryKeys: string[] = Object.keys(this.taskCategories).filter(
      key => !isNaN(Number(this.taskCategories[key]))
    );
    

    For more details check this answer

    To send the selected option to the backend you need to make use of the HttpClient. The usual way is to import it in a service and do something similar to:

    sendData(payload) {
      return this.http.post(this.url, payload);
    }
    

    Then in your component:

    // Todo: bind to a button
    sendData() {
      this.appService.sendData(this.selectedCategory).subscribe(res => {
        // handle response
      });
    }
    

    I recommend reading up on it here

    Working example