我使用的是Angular 2 (TypeScript)。

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

<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 with the new selectedDevice, but what I
    // get here is always the last selection, not the one I just selected.
}

当前回答

角7/8

从angular 6开始,在响应式表单指令中使用ngModel input属性已经被弃用并在angular 7+中被完全移除。点击这里阅读官方文件。

使用响应式表单方法,您可以获得/设置选定的数据为;

      //in your template
 <select formControlName="person" (change)="onChange($event)"class="form-control">
    <option [value]="null" disabled>Choose person</option>
      <option *ngFor="let person of persons" [value]="person"> 
        {{person.name}}
    </option>
 </select> 


 //in your ts
 onChange($event) {
    let person = this.peopleForm.get("person").value
    console.log("selected person--->", person);
    // this.peopleForm.get("person").setValue(person.id);
  }

其他回答

最新的离子3.2.0修改为ionChange

例如: 超文本标记语言

<ion-select (ionChange)="function($event)"> <ion-option>1<ion-option>
</ion-select>

TS

function($event){
// this gives the selected element
 console.log($event);

}

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

<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 ...
}

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

<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>并使用新的表单API

我也有同样的问题,我用下面的代码解决了:

(change)="onChange($event.target.value)"

在angular 6及以上使用selectionChange。例子 (selectionChange) = onChange (event.value美元)

你可以通过在选择标签#device上创建一个引用变量来将值传递回组件,并将它传递给更改处理程序onChange($event, device.value)应该有新值

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

onChange($event, deviceValue) {
    console.log(deviceValue);
}