Search code examples
htmlangularjstypescriptdrop-down-menuangular-ngmodel

ngModel with select list


I am having trouble outputting a value from a select element.

<select 
([ngModel])="office_hour_start" 
name="office_hour_start">
  <option 
    *ngFor="let time of times"
    value="{{time.i}}">
    {{ time.i }}
  </option>
</select>

This setup has worked for me here:

<select 
  [(ngModel)]="employee_id" 
  name="employee_id" 
  class="form-control">
    <option 
      *ngFor="let employee of employees"
      value="{{employee.id}}">
      {{ employee.name }}
    </option>
</select>

Solution

  • On the setup that worked for you, One additional suggestion would be:

    // When using an ngModel, an event emitter () should be inside the input [] always 
    // Though there is an instance where you can use it separately [ngModel] for Input (ngModelChange) for event emitter
    <select [(ngModel)]="employee_id"           
            name="employee_id" 
            class="form-control">
    
        <option *ngFor="let employee of employees"
                value="{{employee.id}}">       // use [value]="employee.id" if you're assigning a dynamic value
            {{ employee.name }}
        </option>
    
    </select>
    

    And for the case of the office_hour_start is its ngModel. You used ([ngModel])="office_hour_start" instead of [(ngModel)]="office_hour_start" putting the parenthesis inside the brackets [] is the way to fix it.

    Had created a Stackblitz Demo for your reference