Angular 2、设置表单中文本输入的值

Angular 2, set value of text inputs in form

所以我正在尝试一些 Angular 2,到目前为止我很喜欢。但是我需要一些帮助来驾驭这个新环境。

我有一个用于编辑用户详细信息的表单和一个包含我所有用户的列表。当我单击列表中的一个用户时,我想用用户详细信息 (setEditForm(user)) 填充我的编辑用户表单。

我已经让它正常工作了。但我必须说,同时使用 ngControl 和 ngModel 感觉不太对。但也许是...

这是执行此操作的正确方法还是我只是运气好让它起作用?

@Component({
  template: `
    <form (ngSubmit)="editUser(f.value)" #f="ngForm">
      <input ngControl="nameInp" [ngModel]="selectedUser.name" type="text">
      <input ngControl="ageInp" [ngModel]="selectedUser.age" type="text">
      <input ngControl="cityInp" [ngModel]="selectedUser.city" type="text">

      <button type="submit">Save</button>
    </form>
)}

export class AdminComponent {
 selectedUser:UserModel;

 constructor() {
    this.selectedUser = new UserModel;
  }

  setEditForm(user:UserModel) {
    this.selectedUser = user;
  }

  editUser(form:any) {
    // Update DB with values
    console.log(form['nameInp']);
    console.log(form['ageInp']);
    console.log(form['cityInp']);
  }
}

当然可以同时使用 ngControl / ngFormControlngModel。来自 Angular2 文档 (https://angular.io/docs/ts/latest/guide/forms.html):

  • two-way data binding with [(ngModel)] syntax for reading and writing values to input controls

  • using ngControl to track the change state and validity of form controls

  • displaying validation errors to users and enable/disable form controls

  • sharing information among controls with template local variables

简而言之,如果我需要双向绑定,我会使用 ngModel,如果我需要验证,我会使用 ngForm / ngFormControl,但您可以混合使用两者。

如果您只需要在输入值更新时获取值和通知,ngControl / ngFormControl` 就足够了...

两者都允许检测变化:

  • 事件 ngModelChange
  • 订阅ctrl.valueChanges

您可以为表单元素 ngModel 配置双向绑定:

<form (ngSubmit)="editUser(f.value)" #f="ngForm">
  <input ngControl="nameInp" [(ngModel)]="selectedUser.name" type="text">
  <input ngControl="ageInp" [(ngModel)]="selectedUser.age" type="text">
  <input ngControl="cityInp" [(ngModel)]="selectedUser.city" type="text">

  <button type="submit">Save</button>
</form>