【问题标题】:Is it possible to have an Angular 2 formGroup without a form tag?是否可以有一个没有表单标签的 Angular 2 formGroup?
【发布时间】:2016-11-15 16:31:46
【问题描述】:

我正在寻找 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>

我正在尝试避免使用嵌套的表单标签

【问题讨论】:

    标签: angular forms tags angular-reactive-forms angular-forms


    【解决方案1】:

    您正在寻找的是 formGroupName 指令

    该指令只能与父 FormGroupDirective 一起使用 (选择器:[formGroup])。

    它接受您要链接的嵌套 FormGroup 的字符串名称, 并将在父级中查找使用该名称注册的 FormGroup 您传递给 FormGroupDirective 的 FormGroup 实例。

    当您想要验证一个表单时,嵌套表单组可以派上用场 表单的子组与其他表单分开或当您想要时 将某些控件的值分组到它们自己的嵌套对象中。

    https://angular.io/docs/ts/latest/api/forms/index/FormGroupName-directive.html

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

    根据文档,在某些时候需要在 &lt;form [formGroup]="formProperty"&gt; 中进行合法定义,并避免使用多个 &lt;form&gt; 标签。

    如果您有一个子组件,您仍然需要[formGroup],但它可以不在&lt;form&gt; 标记中。如果您想在一个大表单中使用它,那么您需要从父级输入您的 FormGroup 并将其设置为:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-31
      • 2018-04-04
      • 2017-03-27
      • 2016-02-26
      • 1970-01-01
      • 2019-02-10
      • 1970-01-01
      • 2017-04-04
      相关资源
      最近更新 更多