1

我有一个这样的模板驱动表单:

<form #f="ngForm" (submit)="onSubmit(f.value)">
  <input type="text" name="name" [ngModel]="person.name">
  <input type="text" name="ssn"  [ngModel]="person.ssn">
  <button type="submit">Submit</button>
</form>

我想用它来创建和编辑人员记录。如果我输入一些值并单击提交按钮f.value是这样的:

{ name: 'John', ssn: '1234567' }

它按原样工作,但我希望我的表单模板不那么冗长。我想避免在编辑时将每个输入绑定到表单值对象的相应属性。是否可以将整个对象绑定到表单值?

我希望能够将先前检索到的对象绑定f.value到表单,但不能。

我猜这应该可行,但它没有:

<form #f="ngForm" (submit)="onSubmit(f.value)" [ngModel]="person">
  <input type="text" name="name" ngModel>
  <input type="text" name="ssn" ngModel>
  <button type="submit">Submit</button>
</form>

这也不起作用:

<form #f="ngForm" (submit)="onSubmit(f.value)" [value]="person">
  <input type="text" name="name" ngModel>
  <input type="text" name="ssn" ngModel>
  <button type="submit">Submit</button>
</form>

实现简洁优雅的表单模板的最佳方式是什么?

4

0 回答 0