我使用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. }
如果你不需要双向数据绑定:
原文链接:https://www.f2er.com/angularjs/146912.html<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 ... } }