Interfector
Interfector

Reputation: 1898

Angular2 select 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?

Upvotes: 1

Views: 1800

Answers (3)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657841

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

Upvotes: 1

Rose Nettoyeur
Rose Nettoyeur

Reputation: 919

I guess you only want the id in your handleChange() method?

How do you access the id in your method?

Try this one:

handleChange(evt) {
    let id = (<HTMLInputElement>event.target).value;
}

The shape of the $event object is determined by whatever raises the event. The event comes from the DOM, so $event must be a standard DOM event object. The $event.target gives us an HTMLInputElement, which has a value property that contains the id.

See also Angular Docu

Upvotes: 1

Rehban Khatri
Rehban Khatri

Reputation: 954

Yes, even I faced it earlier. I changed [value] to [attr.value] and it started working. I hope it works for you too..

Check out other changes in beta 14 and 15 here

Upvotes: 1

Related Questions