如何在“选择"中获得新选择?在 Angular 2 中? [英] How can I get new selection in "select" in Angular 2?

查看:29
本文介绍了如何在“选择"中获得新选择?在 Angular 2 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Angular 2 (TypeScript).

I am using Angular 2 (TypeScript).

我想对新选择做一些事情,但我在 onChange() 中得到的总是最后一个选择.我怎样才能获得新的选择?

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

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

推荐答案

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

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

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

onChange(deviceValue) {
    console.log(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>
</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:


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>
</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 - 不使用


Plunker - 使用 并使用新的表单 API


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

这篇关于如何在“选择"中获得新选择?在 Angular 2 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆