我正在寻找Angular 2 documentation,但是没有办法找到关于如何使用formgroup的最佳实践。
必须用表单标记将formGroup括起来吗?
我已经看了这个堆栈溢出问题:
formGroup expects a FormGroup instance
我已创建此组件模板:

<div [formGroup]="infoIdentityForm">
  <div class="info-identity_title" *ngIf="showTitle">
    <div class="group-title">Titre</div>
    <div class="group-radio">
      <span *ngFor="let choice of enumTitleValue">
        <label>{{choice}}</label>
        <input type="radio" formControlName="title" name="title" [id]="choice"/>
      </span>
    </div>
  </div>
  <div class="info-identity_firstname">
    <div class="group-title">Prénom</div>
    <div class="group-input">
      <input type="text" class="form-control" formControlName="firstName" maxlength="25">
    </div>
  </div>
  <div class="info-identity_lastname">
    <div class="group-title">Nom</div>
    <div class="group-input">
      <input type="text" class="form-control" formControlName="lastName" maxlength="25">
    </div>
  </div>
</div>

我试图避免使用嵌套的表单标记

最佳答案

你要找的是formGroupName指令
此指令只能与父formgroupdirective一起使用
(选择器:[formgroup])。
它接受要链接的嵌套窗体组的字符串名称,
并将在父级中查找以该名称注册的窗体组
传入formgroupdirective的formgroup实例。
如果要验证
一个表单的子组,与其他表单分开,或者当您希望
将某些控件的值分组到它们自己的嵌套对象中。
https://angular.io/docs/ts/latest/api/forms/index/FormGroupName-directive.html

<div formGroupName="infoIdentityForm">
</div>

根据文档,它需要在一个<form [formGroup]="formProperty">中的某个点上进行合法定义,并避免使用多个<form>标记。
如果您有一个子组件,您仍然需要[formGroup],但它不能在<form>标记中。如果你想在一个大的表单中使用它,那么你需要从父表单中输入你的表单组,并将其设置为:
<td [formGroup]="parentGroup">
  <input type="text" formControlName="myControl"
</td>

@Input() parentGroup: FormGroup;

10-05 20:46
查看更多