关于打字稿:如何在Angular 2中的“选择”中获得新选择?

How can I get new selection in “select” in Angular 2?

我用的是角2(打字稿)。

我想为新的选择做些什么,但在onchange()中得到的总是最后一个选择。如何获得新的选择?

1
2
3
4
5
6
7
8
9
<select [(ngModel)]="selectedDevice" (change)="onChange($event)">
    <option *ngFor="#i of devices">{{i}}</option>
</select>

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

如果不需要双向数据绑定:

1
2
3
4
5
6
7
<select (change)="onChange($event.target.value)">
    <option *ngFor="let i of devices">{{i}}</option>
</select>

onChange(deviceValue) {
    console.log(deviceValue);
}

对于双向数据绑定,请分离事件绑定和属性绑定:

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

如果devices是对象数组,则绑定到ngValue而不是value上:

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

PLUNKER-不使用

PLUNKER-使用

并使用新的表单API