小编典典

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

html

我想将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。

但是,我实际上想绑定到country对象本身,所以它selectedValue是对象,而不仅仅是id。我试图像这样更改选项的值:

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

但这似乎不起作用。它似乎在我的对象中放置了一个对象,selectedValue但是没有放置我期望的对象。您可以在我的Plunker示例中看到这一点。

我还尝试绑定到change事件,以便可以根据所选的id自己设置对象;但是,似乎更改事件在绑定的ngModel更新之前就触发了-
这意味着我当时无法访问新选择的值。

有没有一种干净的方法可以将选择元素绑定到具有Angular 2的对象?


阅读 539

收藏
2020-05-10

共1个答案

小编典典

My Application

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

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

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

更新

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

另请参阅 自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;
}
2020-05-10