将选择元素绑定到Angular 2中的对象

我是Angular2的新手,试图用新的方式来加快速度。

我想将一个select元素绑定到一个对象列表 – 这很简单:

@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。

但是,我真的想绑定到国家对象本身,以便selectedValue是对象,而不仅仅是id。 我试图改变这样的选项的价值:

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

但是这似乎不起作用。 它似乎将一个对象放在我的selectedValue中 – 但不是我期望的对象。 你可以在我的Plunker例子中看到这个 。

我也尝试绑定到更改事件,以便我可以基于选定的ID自己设置对象; 然而,看起来更改事件在更新绑定ngModel之前触发 – 这意味着我没有权限访问新选定的值。

有没有一种干净的方式来绑定选择元素与Angular 2的对象?

 <h1>My Application</h1> <select [(ngModel)]="selectedValue"> <option *ngFor="let c of countries" [ngValue]="c">{{c.name}}</option> </select> 

Plunker例子

注意:您可以使用[ngValue]="c"而不是[ngValue]="c.id" ,其中c是完整的国家对象。

[value]="..."仅支持字符串值
[ngValue]="..."支持任何类型

更新

如果value是对象,则预选实例需要与其中一个值相同。

另请参阅自4.0.0-beta.7以来最近添加的自定义比较https://github.com/angular/angular/issues/13268

 <select [compareWith]="compareFn" ... 

这可能有助于:

 <select [(ngModel)]="selectedValue"> <option *ngFor="#c of countries" [value]="c.id">{{c.name}}</option> </select> 

你也可以这样做,而不需要在你的<select>标签中使用[(ngModel)]

在你的ts文件中声明一个变量

toStr = JSON.stringify;

并在你的模板做到这一点

  <option *ngFor="let v of values;" [value]="toStr(v)"> {{v}} </option> 

然后使用

 let value=JSON.parse(event.target.value) 

将字符串解析回有效的JavaScript对象

您可以使用功能选择ID

 <option *ngFor="#c of countries" (change)="onchange(c.id)">{{c.name}}</option> 

您也可以在click()的帮助下通过将选定的值传递给函数来获得选定的值

 <md-select placeholder="Select Categorie" name="Select Categorie" > <md-option *ngFor="let list of categ" [value]="list.value" (click)="sub_cat(list.category_id)" > {{ list.category }} </md-option> </md-select>