FormArrayDirective

The ReactiveForms API provides a set of attribute directives to bind simple to complex forms to your template. These directives matches available classes on Component side: FormGroup, FormControl and FormArray.

For each of theses classes, there are two directives available:

  • one to bind directly a control to a DOM element: [formGroup], [formControl], [formArray]
  • one to bind the key of the control: formGroupName, formControlName, formArrayName

But before v21 We were missing the [formArray] directive.

Sometimes a form is only made of a FormArray and we had to wrap it in a FormGroup:

const form = new FormGroup({
users: new FormArray([
new FormGroup({
firstName: new FormControl(""),
}),
]),
});
<form [formGroup]="form">
<ul formArrayName="users">
@for (user of form.controls.users.controls; track user; let index = $index)
{
<li [formGroupName]="index">
<input type="text" formControlName="firstName" />
</li>
</ul>
</form>

But now you can use the [formArray] directive to bind the FormArray directly to the DOM element:

const form = new FormArray([
new FormGroup({
firstName: new FormControl(""),
}),
]);
<form [formArray]="form">
<ul>
@for (user of form.controls; track user; let index = $index) {
<li [formGroupName]="index">
<input type="text" formControlName="firstName" />
</li>
</ul>
</form>

Exercise

Update the existing form not to depend on the formGroup directive anymore. Use above explanation and code example to help you.

Powered by WebContainers
Files
Preparing Environment
  • Installing dependencies
  • Start the application