Sub topic 2
Adding, Inserting, and Removing Controls
Assume you know FormControl, FormGroup, validators, and standalone Angular components. A FormArray stores controls in order and can change length while the application runs.
Repeating Groups of Fields
Use a FormArray when each repeated item has the same fields. FormGroup models one item; FormArray models the list.
import { Component, inject } from '@angular/core';
import {
NonNullableFormBuilder,
ReactiveFormsModule,
Validators,
} from '@angular/forms';
@Component({
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form" (ngSubmit)="submit()">
<div formArrayName="items">
@for (item of items.controls; track item; let i = $index) {
<div [formGroupName]="i">
<input formControlName="name" placeholder="Item name" />
<input type="number" formControlName="quantity" />
<button type="button" (click)="removeItem(i)">Remove</button>
</div>
}
</div>
<button type="button" (click)="addItem()">Add item</button>
<button type="submit" [disabled]="form.invalid">Submit</button>
</form>
`,
})
export class OrderFormComponent {
private fb = inject(NonNullableFormBuilder);
form = this.fb.group({
items: this.fb.array([this.createItem()]),
});
get items() {
return this.form.controls.items;
}
createItem(name = '', quantity = 1) {
return this.fb.group({
name: [name, Validators.required],
quantity: [quantity, [Validators.required, Validators.min(1)]],
});
}
addItem() {
this.items.push(this.createItem());
}
insertItem(index: number) {
this.items.insert(index, this.createItem('Inserted item'));
}
removeItem(index: number) {
this.items.removeAt(index);
}
clearItems() {
this.items.clear();
}
submit() {
console.log(this.form.getRawValue());
}
}formArrayName selects the array. [formGroupName]="i" selects the group at index i. Use track item so Angular tracks each control object when rows move.
Reading and Submitting the Value
items.value returns enabled controls as an array. form.getRawValue() includes disabled controls. Submit the form only after checking validity, or disable the submit button as shown.
Validation for Entries and the Whole Array
Control validators validate each row. An array validator validates the list itself, such as requiring at least one item.
Exercise
Which method inserts a control at a specific position, and which method removes one by index?
Show answer
insert(index, control) inserts a control, and removeAt(index) removes one.