Angular 2中的formGroup有没有可能不带form标签?



我正在寻找Angular 2文档,没有办法找到关于如何使用formGroup的最佳实践。

是否必须将formGroup包含在表单标记中?

我已经看了这个堆栈溢出问题:

formGroup期望一个formGroup实例

我已经创建了这个组件模板:
<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])。

它接受你想要链接的嵌套FormGroup的字符串名称,并将在父目录中查找以该名称注册的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>标签。如果你想在一个大的表单中使用它,那么你需要从父类中输入FormGroup,并将其设置为:

<td [formGroup]="parentGroup">
  <input type="text" formControlName="myControl"
</td>
@Input() parentGroup: FormGroup;

最新更新