Sub topic 6
Adding, inserting and removing controls
This chapter assumes you know FormControl, FormGroup and Validators. It also assumes you can write a standalone Angular component that imports ReactiveFormsModule. Here you will change a FormArray at runtime.
The mutation methods
A FormArray keeps its children in an ordered list. You change that list with methods on the array, not by editing a plain JavaScript array.
| Method | Effect |
|---|---|
| `push(control)` | Adds a control at the end |
| `insert(index, control)` | Adds a control at a position and shifts later ones right |
| `removeAt(index)` | Removes the control at a position |
| `setControl(index, control)` | Replaces the control at a position |
| `clear()` | Removes every control |
| `at(index)` | Returns the control at a position without changing anything |
The following example uses all three core methods and traces the result.
import { FormArray, FormControl, Validators } from '@angular/forms';
const emails = new FormArray([
new FormControl('[email protected]', { nonNullable: true, validators: [Validators.email] }),
]);
emails.push(new FormControl('', { nonNullable: true, validators: [Validators.email] }));
emails.insert(0, new FormControl('[email protected]', { nonNullable: true }));
emails.removeAt(1);
console.log(emails.length); // 2
console.log(emails.value); // ['[email protected]', '']Follow the list step by step. After push it is [a, '']. After insert(0, ...) it is [first, a, '']. After removeAt(1) the control for [email protected] is gone, leaving [first, ''].
Why you must use these methods
Each method does more than change the list. It also recalculates the array's value, valid and status. It then emits on valueChanges and statusChanges, and the template re-renders the rows. Editing emails.controls directly skips these steps, and the form goes out of sync.
Add and remove from a component
Keep the creation of a new row in one factory method. Then adding a row is a single call.
import { Component, inject } from '@angular/core';
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
@Component({
selector: 'app-tag-form',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<div>
@for (tag of tags.controls; track tag; let i = $index) {
<div>
<input [formControl]="tag" />
<button type="button" (click)="removeTag(i)">Remove</button>
</div>
}
</div>
<button type="button" (click)="addTag()">Add tag</button>
`,
})
export class TagFormComponent {
private fb = inject(NonNullableFormBuilder);
tags = this.fb.array([this.fb.control('', Validators.required)]);
addTag() {
this.tags.push(this.fb.control('', Validators.required));
this.tags.markAsDirty();
}
removeTag(index: number) {
this.tags.removeAt(index);
this.tags.markAsDirty();
}
}The template passes each control to [formControl] directly. Binding with formArrayName is covered in the previous chapter.
Things that catch people out
- Programmatic changes do not mark the form dirty.
pushandremoveAtleavedirtyandtouchedalone. If you show a "unsaved changes" warning, callmarkAsDirty()yourself, as the example does. - Indexes shift after a removal. If you remove rows in a loop, go from the last index to the first. Otherwise you skip rows or remove the wrong one.
- Every change emits events. Adding 50 rows with
pushfires 50 rounds ofvalueChanges. Pass{ emitEvent: false }topushorclearwhile you build the array, then callupdateValueAndValidity()once. - Do not share one control between rows. Create a new control for each
push. A shared instance would make two rows edit the same value. clear()leaves an empty array. If your validator needs at least one row, the array becomes invalid until you add one.
Exercise
A FormArray holds controls for [x, y, z]. You run arr.insert(1, new FormControl('w')) and then arr.removeAt(2). What is arr.value?
Show answer
['x', 'w', 'z']. After the insert the list is [x, w, y, z]. Index 2 is now y, so removeAt(2) removes y.