【问题标题】:Binding ngModel to a model for a select control [duplicate]将ngModel绑定到选择控件的模型[重复]
【发布时间】:2016-04-01 08:55:12
【问题描述】:

在 Angular 1.x 中,您可以将 ngModel 绑定到模型以用于选择控件:

<select ng-model="selectedPerson" 
   ng-options="person as person.name for person in people">
</select>

选中选项时,selectedPerson Model将指向用户所选的person Model。

有没有办法在 Angular2 中做同样的事情?

我尝试了以下方法,但没有成功:

<select [(ngModel)] = "selectedPerson"> 
     <option *ngFor="#person of people"> {{ person.name }}</option>
</select>

我也试过了:

<select [(ngModel)] = "selectedPerson"> 
     <option *ngFor="#person of people" [value]="person"> {{ person.name }}</option>
</select>

在第一次尝试中,selectedPerson 模型引用 person.name 而不是 person 对象。在第二次尝试中,它引用了一个对象,该对象似乎不是 JSON 对象。

任何想法我做错了什么?这甚至可能吗?

【问题讨论】:

标签: angular


【解决方案1】:

您可以使用FormBuilder 指令在表单内实现&lt;select&gt;:

import { FormBuilder, Validators } from '@angular/forms';

export class LoginPage {

  constructor(form: FormBuilder) {
    this.cities = ["Shimla", "New Delhi", "New York"]; // List of cities
    this.loginForm = form.group({
      username: ["", Validators.required],
      password: ["", Validators.required],
      city: ["", Validators.required] // Setting the field to "required"
    });
  }

  login(ev) {
    console.log(this.loginForm.value); // {username: <username>, password: <password>, city: <city>}
  }

}

在您的 .html 中:

<form [ngFormModel]="loginForm" (submit)="login($event)">

    <input type="text" ngControl="username">
    <input type="password" ngControl="password">
    <select ngControl="city">
        <option *ngFor="#c of cities" [value]="c">{{c}}</option>
    </select>
    <button block type="submit" [disabled]="!loginForm.valid">Submit</button>

</form>

Official Documentation

【讨论】:

  • 这不是我想要的。使用 ngControl 仍然绑定到输入控件的值,而不是模型。选择下拉列表时,我试图将 selectedPerson 绑定到模型 { name:'' } 而不仅仅是名称。尝试更新您的示例以使用以城市为对象的模型:{ name: }。你会看到 loginForm.city 只是一个字符串。
  • @pixelbits 为什么不简单地在构造函数中设置this.selectedPerson = {},然后在选项中设置[(ngModel)] = "selectedPerson.name" 和[value]=person.name?这将导致:selectedPerson: {name: "&lt;name&gt;"}.
  • 这与绑定到模型不同。我可以从数据库中检索这些对象。我正在寻找相当于 ng-options="person as person.name for person in people"
【解决方案2】:

我在尝试将对象作为选定值传递给 ngModel 时遇到同样的问题。我看到的另一种解决方案是使用传递给字符串的对象的字符串化版本,但这很脏。

最后我决定在传递给 ngModel 的对象中创建一个单独的索引。我用它来选择对象并执行操作。

同样的问题出现在:https://github.com/angular/angular/issues/4843 和How to use select/option/NgFor on an array of objects in Angular2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-16
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    • 2017-10-17
    • 2020-12-07
    • 2011-12-01
    相关资源
    最近更新 更多