我想把一个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更新之前,change事件就触发了——这意味着我在那一点上没有访问新选择的值。

在Angular 2中,是否有一种简洁的方法将选择元素绑定到对象?


当前回答

对我来说,它是这样工作的,你可以console event。target。value。

<select (change) = "ChangeValue($event)" (ngModel)="opt">   
    <option *ngFor=" let opt of titleArr" [value]="opt"></option>
</select>

其他回答

这可能会有所帮助:

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

此外,如果从给定的解决方案没有其他工作,检查你是否导入了“FormsModule”在“AppModule”,这是我的一个关键。

在app.component.html:

<select type="number" [(ngModel)]="selectedLevel">
  <option *ngFor="let level of levels" [ngValue]="level">{{level.name}}</option>
</select>

和app.component.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  levelNum:number;
  levels:Array<Object> = [
      {num: 0, name: "AA"},
      {num: 1, name: "BB"}
  ];

  toNumber(){
    this.levelNum = +this.levelNum;
    console.log(this.levelNum);
  }

  selectedLevel = this.levels[0];

  selectedLevelCustomCompare = {num: 1, name: "BB"}

  compareFn(a, b) {
    console.log(a, b, a && b && a.num == b.num);
    return a && b && a.num == b.num;
  }
}

用这种方式也可以。

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

为所选项目创建另一个getter

<form [formGroup]="countryForm">
  <select formControlName="country">
    <option *ngFor="let c of countries" [value]="c.id">{{c.name}}</option>
  </select>

  <p>Selected Country: {{selectedCountry?.name}}</p>
</form>

在ts中:

get selectedCountry(){
  let countryId = this.countryForm.controls.country.value;
  let selected = this.countries.find(c=> c.id == countryId);
  return selected;
}