typescript – 如何在Angular 2的“select”中获得新的选择?

前端之家收集整理的这篇文章主要介绍了typescript – 如何在Angular 2的“select”中获得新的选择?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用Angular 2(TypeScript)。

我想做一些新的选择,但我得到的onChange()总是最后的选择。如何获得新的选择?

<select [(ng-model)]="selectedDevice" (change)="onChange($event)">
    <option *ng-for="#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.
}
如果你不需要双向数据绑定:
<select (change)="onChange($event.target.value)">
    <option *ngFor="let i of devices">{{i}}</option>
</select>

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

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

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

如果设备是对象数组,请绑定到ngValue而不是值:

<select [ngModel]="selectedDeviceObj" (ngModelChange)="onChangeObj($event)" name="sel3">
  <option [ngValue]="i" *ngFor="let i of deviceObjects">{{i.name}}</option>
</select>
{{selectedDeviceObj | json}}
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 – 不使用< form>
Plunker – 使用< form>并使用新的表单API

猜你在找的Angularjs相关文章