首页 文章

将ngModel绑定到选择控件的模型[重复]

提问于
浏览
10

这个问题在这里已有答案:

在Angular 1.x中,您可以将ngModel绑定到select控件的模型:

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

选择选项后, selectedPerson 模型将指向用户选择的 person 模型 .

有没有办法在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对象的对象 .

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

2 回答

  • 1

    您可以使用 FormBuilder 指令在表单中实现 <select>

    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

  • 4

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

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

    还提出了以下问题:https://github.com/angular/angular/issues/4843How to use select/option/NgFor on an array of objects in Angular2

相关问题