2016-11-15 59 views
1

我期待Angular 2 documentation,并且没有办法找到如何使用formGroup的最佳做法。是否有可能没有窗体标签的Angular 2 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> 

我想avoid the use of nested form tags

回答

6

什么你要找的是formGroupName指令

这个指令只能与父母FormGroupDirective (选择:formGroup])使用。

它接受您要链接的嵌套FormGroup的字符串名称, ,并且会在您传递到FormGroupDirective的父级 FormGroup实例中查找使用该名称注册的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; 
+0

酷招,为我工作的好! – Abdel

相关问题