I'm looking to Angular 2 documentation, and there is no way to find what is the best practice about how to use formGroup.
Is it mandatory to enclose a
formGroup
with a form tag ?
I've looked to this stack overflow question:
formGroup expects a FormGroup instance
I've created this component template:
<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>
I'm trying to avoid the use of nested form tags
What you're looking for is the formGroupName
directive
This directive can only be used with a parent FormGroupDirective (selector: [formGroup]).
It accepts the string name of the nested FormGroup you want to link, and will look for a FormGroup registered with that name in the parent FormGroup instance you passed into FormGroupDirective.
Nested form groups can come in handy when you want to validate a sub-group of a form separately from the rest or when you'd like to group the values of certain controls into their own nested object.
https://angular.io/docs/ts/latest/api/forms/index/FormGroupName-directive.html
<div formGroupName="infoIdentityForm">
</div>
Which, per the documentation, needs to be in a <form [formGroup]="formProperty">
at some point to be legally defined and avoid multiple <form>
tags being used.
If you have a child component you still need the [formGroup]
but it can be not in a <form>
tag. If you want to use it all in one big form then you'll need to input your FormGroup from the parent and set it like:
<td [formGroup]="parentGroup">
<input type="text" formControlName="myControl"
</td>
@Input() parentGroup: FormGroup;