我怎样才能在与QUOT得到新的选择;选取[在角2? [英] How can I get new selection in "select" in Angular 2?

查看:165
本文介绍了我怎样才能在与QUOT得到新的选择;选取[在角2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我想要做一些新的选择,但我在的onChange有()总是最后的选择。我怎样才能获得新的选择?

 <选择[(NG-模式)] =selectedDevice(变化)=的onChange($事件)>
    <选项* NG换=设备#我> {{I}}< /选项>
< /选择>的onChange($事件){
    的console.log(this.selectedDevice);
    //我想在这里对新selectedDevice做些什么,但我
    //来到这里永远是最后的选择,不是我只是选择。
}


解决方案

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

 <选择(其他城市)=的onChange($ event.target.value)>
    <选项* ngFor =设备#我> {{I}}< /选项>
< /选择>的onChange(deviceValue){
    的console.log(deviceValue);
}

有关的双向数据绑定,我觉得分离事件和财产绑定将工作:

 <选择[ngModel] =selectedDevice(ngModelChange)=的onChange($事件)>
    <选项* ngFor =设备#我> {{I}}< /选项>
< /选择>的onChange(newValue)以{
    的console.log(为newValue);
    this.selectedDevice =为newValue;
    // ...在这里做其他的东西...
}

<击>不过的onChange()函数快速连续叫了两声每个选择列表的变化&ndash的;以及它们固定在<一个href=\"https://github.com/angular/angular/blob/master/CHANGELOG.md#200-beta1-catamorphic-involution-2016-01-08\">beta.1,所以现在的上述溶液的作品相当不错,不像@ Brocco的解决方案,我们不需要定义局部模板变量 #device

<大骨节病> Plunker

I am using Angular 2 (TypeScript).

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

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

解决方案

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

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

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

For two-way data-binding, I thought separating the event and property bindings would work:

<select [ngModel]="selectedDevice" (ngModelChange)="onChange($event)">
    <option *ngFor="#i of devices">{{i}}</option>
</select>

onChange(newValue) {
    console.log(newValue);
    this.selectedDevice = newValue;
    // ... do other stuff here ...
}

But the onChange() function is called twice in rapid succession for each select list change – well they fixed that in beta.1, so now the above solution works quite nicely, and unlike @Brocco's solution, we don't need to define local template variable #device.

Plunker

这篇关于我怎样才能在与QUOT得到新的选择;选取[在角2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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