Hongbo Miao Hongbo Miao - 1 year ago 86
TypeScript Question

How can I get new selection in "select" in Angular 2?

I am using Angular 2 (TypeScript).

I want to do something for new selection, but what I got in onChange() is always last selection. How can I get new selection?

<select [(ng-model)]="selectedDevice" (change)="onChange($event)">
<option *ng-for="#i of devices">{{i}}</option>

onChange($event) {
// I want to do something here for new selectedDevice, but what I
// got here is always last selection, not the one I just select.

Answer Source

If you don't need two-way data-binding:

<select (change)="onChange($event.target.value)">
    <option *ngFor="let i of devices">{{i}}</option>

onChange(deviceValue) {

For two-way data-binding, separate the event and property bindings:

<select [ngModel]="selectedDevice" (ngModelChange)="onChange($event)" name="sel2">
    <option [value]="i" *ngFor="let i of devices">{{i}}</option>
export class AppComponent {
  devices = 'one two three'.split(' ');
  selectedDevice = 'two';
  onChange(newValue) {
    this.selectedDevice = newValue;
    // ... do other stuff here ...

If devices is array of objects, bind to ngValue instead of value:

<select [ngModel]="selectedDeviceObj" (ngModelChange)="onChangeObj($event)" name="sel3">
  <option [ngValue]="i" *ngFor="let i of deviceObjects">{{i.name}}</option>
{{selectedDeviceObj | json}}
export class AppComponent {
  deviceObjects = [{name: 1}, {name: 2}, {name: 3}];
  selectedDeviceObj = this.deviceObjects[1];
  onChangeObj(newObj) {
    this.selectedDeviceObj = newObj;
    // ... do other stuff here ...

Plunker - does not use <form>
Plunker - uses <form> and uses the new forms API