我想把一个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中,是否有一种简洁的方法将选择元素绑定到对象?


当前回答

你也可以这样做,而不需要在<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对象

其他回答

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

这段代码非常简单:

<select class="form-control" id="marasemaat" [(ngModel)]="fullNamePresentor" 
        [formControl]="stateControl" (change)="onSelect($event.target.value)">
  <option *ngFor="let char of programInfo1;let i = index;" 
          onclick="currentSlide(9,false)" 
          value={{char.id}}>{{char.title + " "}}  ----> {{char.name + " "+ char.family }} ---- > {{(char.time.split('T', 2)[1]).split(':',2)}}</option>
</select>

您还可以通过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>

以防有人想用响应式表单做同样的事情:

<form [formGroup]="form">
  <select formControlName="country">
    <option *ngFor="let country of countries" [ngValue]="country">{{country.name}}</option>
  </select>
  <p>Selected Country: {{country?.name}}</p>
</form>

在这里查看工作示例

在Angular 11上测试。我需要一个额外的对象'typeSelected'。注意,我没有像其他答案一样使用[(ngValue)]:

<mat-select formControlName="type" [(value)]="typeSelected" 
            [compareWith]="typeComparation">
  <mat-option *ngFor="let myType of allSurveysTypes" [value]="myType">
    {{myType.title}}
  </mat-option>
</mat-select>
//Declaration.
typeSelected: SurveyType;
...

//Assigning variable 'type' of object 'survey' to 'typeSelected'.
this.typeSelected = survey?.type;
...

    
//Function to compare SurveyType objects.
typeComparation = ( option, value ) =>  {
  if (option && value) {
    return option.id === value.id;
  }
}