绑定选择元素角2对象 [英] Binding select element to object in Angular 2

查看:122
本文介绍了绑定选择元素角2对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来Angular2并试图获得了做事情的新方式加速。

I'm new to Angular2 and trying to get up to speed with the new way of doing things.

我想一个select元素绑定到对象的列表 - 这是很容易的:

I'd like to bind a select element to a list of objects -- which is easy enough:

@Component({
   selector: 'myApp',
   template: `<h1>My Application</h1>
              <select [(ngModel)]="selectedValue">
                 <option *ngFor="#c of countries" value="c.id">{{c.name}}</option>
              </select>`
})
export class AppComponent{
    countries = [
       {id: 1, name: "United States"},
       {id: 2, name: "Australia"}
       {id: 3, name: "Canada"}
       {id: 4, name: "Brazil"}
       {id: 5, name: "England"}
     ];
    selectedValue = null;
}

在这种情况下,似乎了selectedValue将是一个数 - 所选择的项目的id

In this case, it appears that selectedValue would be a number -- the id of the selected item.

不过,其实我要绑定到全国对象本身,使了selectedValue是对象而不仅仅是ID。我试图改变选项的值,像这样:

However, I'd actually like to bind to the country object itself so that selectedValue is the object rather than just the id. I tried changing the value of the option like so:

<option *ngFor="#c of countries" value="c">{{c.name}}</option>

但这似乎并没有工作。这似乎放在我了selectedValue一个对象 - 但不是我期待的对象。您可以看到这在我的Plunker例如

我也试过绑定到更改事件,这样我可以根据所选择的ID设置对象自己;然而,现在看来,势必ngModel前的变化事件触发更新 - 这意味着我不必在这一点上获得了新选择的值

I also tried binding to the change event so that I could set the object myself based on the selected id; however, it appears that the change event fires before the bound ngModel is updated -- meaning I don't have access to the newly selected value at that point.

是否有一个选择的元素结合到与角2的对象?

Is there a clean way to bind a select element to an object with Angular 2?

推荐答案

有是与火狐的 https://github.com/angular/angular/issues/6573

选择目前还不支持对象作为值 https://github.com/angular/角/问题/ 4843

Select currently also doesn't support objects as values https://github.com/angular/angular/issues/4843.

一个解决方法是在<一个解释href=\"http://stackoverflow.com/questions/33181936/how-to-use-select-option-ngfor-on-an-array-of-objects-in-angular2\">How对象在Angular2 阵列上使用select /选项/ NgFor

A workaround is explained in How to use select/option/NgFor on an array of objects in Angular2

这篇关于绑定选择元素角2对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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