Abhijeet
Abhijeet

Reputation: 13856

How to Bind Selected Drop Down Value directly as enum?

How to Bind Selected Drop Down Value directly as enum?

.html file

<div class="form-group">
    <label for="department">Department</label>
    <select name="department" [(ngModel)]="selectedValue" 
            #selDept 
            (change) = "onDepartmentChange(selDept.value)"
            class="form-control">
      <option *ngFor="let dept of departments" [value]="dept.id">
        {{dept.name}}
      </option>
          </select>
  </div>

.ts file

import { Component, OnInit } from '@angular/core';
import { Department, DepartmentEnum } from './models/department.model';

@Component({
  selector: 'app-ddl',
  templateUrl: './ddl.component.html',
  styleUrls: ['./ddl.component.css']
})
export class DdlComponent implements OnInit {

  constructor() { 
    this.selectedValue = 1;
  }

  ngOnInit(): void {
  }

  selectedValue: DepartmentEnum; //Can NgModel be directly typecasted into Enum


  departments: Department[] = [
    { id: 1, name: 'One' },
    { id: 2, name: 'Two' },
    { id: 3, name: 'Three' }
  ];

  onDepartmentChange(changedValue: any){
    debugger;
    console.log(`hi, you changed me, to ${changedValue}`);
  }
}

Enum File

export enum DepartmentEnum{
    NA = 0,
    A = 1,
    B = 2
}

Upvotes: 2

Views: 284

Answers (1)

Deepu Reghunath
Deepu Reghunath

Reputation: 9693

selectedValue holds a single value. You can assign one of the enum value to it.

this.selectedValue = DepartmentEnum.B;

You need id and name to list the select options. and you can assign the enum value to the id by using enum name.

departments: Department[] = [
 { id: DepartmentEnum.A, name: 'One' },
 { id: DepartmentEnum.B, name: 'Two' },
 { id: DepartmentEnum.NA, name: 'Three' }
];

Stackblits solution

Upvotes: 1

Related Questions