Angular2 select issue

Issue

The following code used to work in Angular 2 beta 13:

<select (change)="handleChange($event)">
    <option value="">-- please choose an option --</option>
    <option *ngFor="#option of options" [value]="option.id">{{ option.name }}</option>
</select>

The options array can be as simple as [{id: 0, name="First"}, {id: 1, name="Second"}]. What I mean by it used to work is that when a new selection was made I was able to get the value of the selected option. Right now the value is the same as the label (innerText of the option).

Now, in beta 14 and 15 the same code does not work anymore. Is it a bug with Angular 2 or was there a breaking change introduced that I need to introduce in my own code?

Solution

You can

  • get the value assigned to an option by looking it up in your options by id

  • or use [ngValue] (introduced in beta.15) to use object values directly

@Component({
    selector: 'my-app',
    template: `
    <div>selected: {{selected1 | json}}</div>
    <select (change)="handleChange($event)">
      <option value="">-- please choose an option --</option>
      <option *ngFor="#option of options" [value]="option.id">{{ option.name }}</option>
    </select>    

    <div>selected: {{selected2 | json}}</div>
    <select [(ngModel)]="selected2">
      <option value="">-- please choose an option --</option>
      <option *ngFor="#option of options" [ngValue]="option">{{ option.name }}</option>
    </select>`
})
export class AppComponent {
  options = [{id: 0, name:"First"}, {id: 1, name:"Second"}];
  selected1;
  selected2 = "";

  handleChange(event) {
    console.log(event.target.value);
    this.selected1 = this.options.filter((option) => {
      return option.id == event.target.value;
    })[0];    

  }
}

Plunker example beta.16

Answered By – Günter Zöchbauer

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.