gpt4 book ai didi

html - 将选择元素绑定(bind)到Angular中的对象

转载 作者:bug小助手 更新时间:2023-10-28 10:55:10 33 4
gpt4 key购买 nike

我想将一个选择元素绑定(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;
}

关于html - 将选择元素绑定(bind)到Angular中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35945001/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com