Sub topic 6
Adding, inserting and removing controls
A FormArray is useful because its list of controls can change while the form is on screen. This chapter covers the methods that change that list, what each one does to the form's state, and the mistakes that cause stale or shared state.
It assumes you can write a component with a FormGroup, you know how formArrayName binds an array in a template (previous chapter), and you use standalone components that import ReactiveFormsModule.
The mutation methods
A FormArray keeps its children in an ordered controls array. Five methods change that array.
| Method | Effect |
|---|---|
| `push(control)` | Appends a control at the end. |
| `insert(index, control)` | Adds a control at `index`. Later controls shift one position up. |
| `removeAt(index)` | Removes the control at `index`. Later controls shift one position down. |
| `setControl(index, control)` | Replaces the control at `index` with another one. |
| `clear()` | Removes every control and leaves an empty array. |
Two read-only helpers go with them. at(index) returns the control at a position, and length returns the current count.
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);
console.log(emails.value);Trace the array through each step:
- It starts as
['[email protected]']. - After
pushit is['[email protected]', '']. - After
insert(0, ...)it is['[email protected]', '[email protected]', '']. - After
removeAt(1)it is['[email protected]', ''].
The code therefore prints 2, then ['[email protected]', ''].
What happens to form state
Each mutation method does three things.
- It changes the
controlsarray. - It registers the form as the new control's parent, or detaches it from a removed control.
- It calls
updateValueAndValidity()on the array, which recomputesvalue,validanderrors. Parent controls are updated as well.
The recalculation is the useful part. A new control with an invalid initial value makes the array and the whole form invalid at once. Removing the only invalid control makes the form valid again. [disabled]="form.invalid" on a submit button therefore follows the list without extra code.
The methods do not update dirty or touched. Adding or removing a row is a change the user made, but Angular only sets dirty when a control's own value is edited through the view. If you use dirty to warn about unsaved changes, mark the form yourself:
remove(index: number) {
this.emails.removeAt(index);
this.form.markAsDirty();
}A removed control's dirty and touched flags go away with it. Say the user edits a row and then deletes it. If you don't call markAsDirty(), the form can go back to looking pristine even though the data changed.
Events and the emitEvent option
Each method accepts an optional second argument, except insert and setControl, where it is the third: { emitEvent: false }. It suppresses valueChanges and statusChanges for that one call. This is helpful when you are building the array in a loop and want one notification at the end rather than one per row.
rows.forEach((row) => this.emails.push(this.createEmail(row), { emitEvent: false }));
this.emails.updateValueAndValidity();The final updateValueAndValidity() call sends a single update. Without it, subscribers never learn that the array changed.
A component that adds, inserts and removes
This component keeps a list of email addresses. Each row has buttons to insert a new row below it and to remove it.
import { Component, inject } from '@angular/core';
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
@Component({
selector: 'app-email-list',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form">
<div formArrayName="emails">
@for (email of emails.controls; track email; let i = $index) {
<div>
<input [formControlName]="i" type="email" />
<button type="button" (click)="insertBelow(i)">Insert below</button>
<button type="button" (click)="remove(i)">Remove</button>
</div>
}
</div>
<button type="button" (click)="add()">Add</button>
<button type="button" (click)="clearAll()">Clear</button>
<p>Rows: {{ emails.length }}</p>
</form>
`,
})
export class EmailListComponent {
private fb = inject(NonNullableFormBuilder);
form = this.fb.group({
emails: this.fb.array([this.createEmail()]),
});
get emails() {
return this.form.controls.emails;
}
createEmail(value = '') {
return this.fb.control(value, Validators.email);
}
add() {
this.emails.push(this.createEmail());
this.form.markAsDirty();
}
insertBelow(index: number) {
this.emails.insert(index + 1, this.createEmail());
this.form.markAsDirty();
}
remove(index: number) {
if (index < 0 || index >= this.emails.length) {
return;
}
this.emails.removeAt(index);
this.form.markAsDirty();
}
clearAll() {
this.emails.clear();
this.form.markAsDirty();
}
}Four details in this component matter.
createEmail()is a factory. Every call returns a newFormControl. This is the most important habit with dynamic arrays, and the next section explains why.[formControlName]="i"binds each input by its index insideformArrayName. The template uses the control's current position, so after a removal the remaining rows get new indexes.track emailtracks each row by its control object. The controls are stable objects, so Angular keeps the matching DOM nodes and the user's cursor position when you insert or remove other rows. Tracking by$indexwould reuse a DOM node for a different control after every shift.- The bounds check in
removeguards against an index that no longer exists. A stale index can arrive when a double click or a deferred callback fires after the list has already changed.
Common mistakes
Pushing the same instance twice
A control is an object with its own state. If you create one FormControl and push it twice, both rows are bound to the same object. Typing in one row changes the other.
const shared = new FormControl('');
emails.push(shared);
emails.push(shared); // Both rows now edit the same control.Build a new control for every row, either through a factory such as createEmail() or by calling fb.control(...) inline.
Removing inside a forward loop
Suppose you want to remove every empty entry. A forward loop skips items, because each removal shifts the next item into the current position.
// Buggy: after removeAt(i), the next control moves to index i and is skipped.
for (let i = 0; i < this.emails.length; i++) {
if (!this.emails.at(i).value) {
this.emails.removeAt(i);
}
}Loop backwards instead. Removing the control at i only shifts controls that have already been checked.
removeEmpty() {
for (let i = this.emails.length - 1; i >= 0; i--) {
if (!this.emails.at(i).value) {
this.emails.removeAt(i, { emitEvent: false });
}
}
this.emails.updateValueAndValidity();
}Replacing the array with a new one
Assigning a new FormArray to a property, such as this.emails = new FormArray([]), does not update the parent group. The group still holds the old array. To swap the array, call this.form.setControl('emails', newArray). To swap one entry, use this.emails.setControl(i, newControl). In most cases clear() followed by push is simpler, because the original array and its validators stay in place.
Expecting setValue to add rows
setValue and patchValue on a FormArray update the controls that already exist. They never create new ones, and setValue throws if the supplied array is longer than the control list. Adding rows is always your job. A later chapter covers loading existing data.
Forgetting that the array can be empty
After clear() or the last removeAt, emails.value is [] and emails.valid is true, because no control is invalid. If your form needs at least one row, an empty array passes unless you add a rule for it. Validators attached to the array do this, and they are covered in a later chapter.
Choosing between insert, push and setControl
- Use
pushfor "add another" buttons where order does not matter. - Use
insertwhen the new row must go next to a particular row, such as "duplicate this line" or drag-and-drop reordering. - Use
setControlwhen one row needs a different kind of control, for example replacing a plainFormControlwith one that has extra validators after the user changes a selection. - Use
clearbefore reloading the whole list from a server response.
Reordering has no dedicated method. To move a row, remove it with removeAt, then insert the same control object at the new index. Moving the existing control keeps the user's input and validation state, whereas creating a new control would lose them.
move(from: number, to: number) {
const control = this.emails.at(from);
this.emails.removeAt(from);
this.emails.insert(to, control);
}Exercise
A form has a FormArray of three rows. A developer writes for (let i = 0; i < rows.length; i++) { if (rows.at(i).invalid) rows.removeAt(i); } and finds that some invalid rows are still there afterwards. Why does this happen, and how do you fix it? Also, what extra step is needed if the form's dirty flag should reflect the removals?
Show answer
When a row is removed, the following rows shift down by one position, so the row that moves into index i is never tested because the loop then increments i. If rows 0 and 1 are both invalid, only row 0 is removed and the row that moved into index 0 is skipped. Fix it by looping backwards, from rows.length - 1 down to 0, so removals only shift rows that have already been checked. FormArray mutations do not mark the form dirty on their own, so call form.markAsDirty() after the removals.