Sub topic 1
Dynamic Forms with FormArray in Angular
Prerequisites
Assume you know TypeScript, Angular components and templates, standalone components, and basic reactive forms with FormControl, FormGroup, and validators.
Quick recap: reactive forms
A reactive form keeps its structure and state in TypeScript. The template connects to that model with directives. This makes validation, dynamic changes, and submission logic explicit.
A FormControl represents one field. A FormGroup combines named controls into an object-shaped value. A FormArray combines controls into an ordered list whose length can change while the application runs.
FormControl and FormGroup in brief
Use a FormGroup when the fields have stable names:
const profile = new FormGroup({
name: new FormControl(''),
email: new FormControl(''),
});Its value resembles { name: '', email: '' }. Use a FormControl for one value and a FormGroup for related, named values.
What FormArray is and when to use it
Use FormArray when users can add, insert, or remove entries, such as email addresses or order lines. Its value is an array, and each position contains the value of one child control.
A FormArray can contain controls, groups, or even other arrays. Its children should usually share the same shape.
Creating a FormArray with FormBuilder
FormBuilder creates controls with less repetition. NonNullableFormBuilder also prevents ordinary controls from producing null values:
import { NonNullableFormBuilder } from '@angular/forms';
constructor(private fb: NonNullableFormBuilder) {}
emails = this.fb.array([
this.fb.control('[email protected]'),
]);
addEmail() {
this.emails.push(this.fb.control(''));
}The emails array can now grow at runtime. Use insert(index, control) to place a control at a position, removeAt(index) to delete one, and clear() to remove every child.
Binding a FormArray in the template
The parent form uses [formGroup]. formArrayName selects the array, and [formControlName] selects a child by index:
<form [formGroup]="form" (ngSubmit)="submit()">
<div formArrayName="emails">
@for (email of emails.controls; track email; let i = $index) {
<input [formControlName]="i" type="email">
<button type="button" (click)="emails.removeAt(i)">Remove</button>
}
</div>
<button type="button" (click)="addEmail()">Add email</button>
<button type="submit">Save</button>
</form>The component must define form with an emails array and import ReactiveFormsModule.
Exercise
Which container fits a user-editable list of order lines whose count changes at runtime?
Show answer
A FormArray, usually containing one FormGroup per order line.