我想将一个选择元素绑定(bind)到一个对象列表——这很简单:
@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。
但是,我实际上想绑定(bind)到 country 对象本身,以便 selectedValue
是对象,而不仅仅是 id。我尝试像这样更改选项的值:
<option *ngFor="#c of countries" value="c">{{c.name}}</option>
但这似乎不起作用。它似乎在我的 selectedValue
中放置了一个对象——但不是我期望的对象。您可以see this in my Plunker example .
我还尝试绑定(bind)到更改事件,以便我可以根据选定的 id 自己设置对象;但是,似乎 change 事件在绑定(bind)的 ngModel 更新之前触发——这意味着我当时无权访问新选择的值。
有没有一种干净的方法可以使用 Angular 2 将选择元素绑定(bind)到对象?
<h1>My Application</h1>
<select [(ngModel)]="selectedValue">
<option *ngFor="let c of countries" [ngValue]="c">{{c.name}}</option>
</select>
StackBlitz example
注意:您可以使用 [ngValue]="c"
而不是 [ngValue]="c.id"
其中 c 是完整的国家对象。
[value]="..."
仅支持字符串值
[ngValue]="..."
支持任何类型
更新
如果 value
是一个对象,预选实例需要与其中一个值相同。
另见最近添加的自定义比较 https://github.com/angular/angular/issues/13268自 4.0.0-beta.7 起可用
<select [compareWith]="compareFn" ...
如果您想访问 this
,请注意在 compareFn
内.
compareFn = this._compareFn.bind(this);
// or
// compareFn = (a, b) => this._compareFn(a, b);
_compareFn(a, b) {
// Handle compare logic (eg check if unique ids are the same)
return a.id === b.id;
}
我是一名优秀的程序员,十分优秀!