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

HTML

小小

2020-03-23

我想将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的对象?

第2647篇《将选择元素绑定到Angular中的对象》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

12个回答
樱小胖Mandy 2020.03.23

<select name="typeFather"
    [(ngModel)]="type.typeFather">
        <option *ngFor="let type of types" [ngValue]="type">{{type.title}}</option>
</select>

该方法总是可行的,但是,如果您有动态列表,请确保在模型之前加载它

阿飞 2020.03.23

您也可以在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>
Mandy村村 2020.03.23

对于我来说,它可以像这样工作,您可以进行控制台event.target.value

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

也用这种方式

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

另外,如果给定解决方案中的所有其他功能均无效,请检查是否在“ AppModule”内部导入了“ FormsModule”,这对我来说很关键。

小宇宙LEY 2020.03.23

为所选项目创建另一个吸气剂

<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;
}
GO 2020.03.23

您也可以这样做,而无需[(ngModel)]<select>标签中使用

在ts文件中声明一个变量

toStr = JSON.stringify;

然后在您的模板中执行此操作

 <option *ngFor="let v of values;" [value]="toStr(v)">
      {{v}}
 </option>

然后使用

let value=JSON.parse(event.target.value)

将字符串解析回有效的JavaScript对象

null 2020.03.23

您可以使用功能选择ID

<option *ngFor="#c of countries" (change)="onchange(c.id)">{{c.name}}</option>
猪猪Mandy 2020.03.23
<h1>My Application</h1>
<select [(ngModel)]="selectedValue">
  <option *ngFor="let c of countries" [ngValue]="c">{{c.name}}</option>
</select>

StackBlitz示例

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

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

更新

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

另请参阅自4.0.0-beta.7起可用的最近添加的自定义比较https://github.com/angular/angular/issues/13268

<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.03.23

这可以帮助:

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

老丝 2020.03.23

它为我工作:

模板HTML:

我加(ngModelChange)="selectChange($event)"select

<div>
  <label for="myListOptions">My List Options</label>
  <select (ngModelChange)="selectChange($event)" [(ngModel)]=model.myListOptions.id >
    <option *ngFor="let oneOption of listOptions" [ngValue]="oneOption.id">{{oneOption.name}}</option>
  </select>
</div>

在component.ts上:

  listOptions = [
    { id: 0, name: "Perfect" },
    { id: 1, name: "Low" },
    { id: 2, name: "Minor" },
    { id: 3, name: "High" },
  ];

您需要添加component.ts到此功能:

  selectChange( $event) {
    //In my case $event come with a id value
    this.model.myListOptions = this.listOptions[$event];
  }

注意:我尝试使用[select]="oneOption.id==model.myListOptions.id"但不起作用。

=============其他方式可以是:=========

模板HTML:

我加[compareWith]="compareByOptionIdselect

<div>
  <label for="myListOptions">My List Options</label>
  <select [(ngModel)]=model.myListOptions [compareWith]="compareByOptionId">
    <option *ngFor="let oneOption of listOptions" [ngValue]="oneOption">{{oneOption.name}}</option>
  </select>
</div>

在component.ts上:

  listOptions = [
    { id: 0, name: "Perfect" },
    { id: 1, name: "Low" },
    { id: 2, name: "Minor" },
    { id: 3, name: "High" },
  ];

您需要添加component.ts到此功能:

 /* Return true or false if it is the selected */
 compareByOptionId(idFist, idSecond) {
    return idFist && idSecond && idFist.id == idSecond.id;
 }
凯西里 2020.03.23

以防万一有人希望使用反应式表单执行相同的操作:

<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>

这里检查工作示例

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android