Sub topic 3
What FormArray is and when to use it
This chapter assumes you know TypeScript, Angular components and templates, and the basics of reactive forms: FormControl, FormGroup and Validators. You should also be comfortable importing ReactiveFormsModule into a standalone component. Template binding, FormBuilder and rendering get their own chapters, so this one focuses on the model: what a FormArray is, how it behaves, and when it is the right choice.
The problem a FormArray solves
A FormGroup has a fixed set of named keys. You decide at design time that the form has firstName, lastName and email, and the shape stays that way. Many forms do not work like that. A user may enter one phone number or five. An order may have two lines or forty. The number of fields is data, not structure.
A FormArray is a control that holds an ordered list of child controls. You can add, insert and remove children while the form is running. Its value is an array of the children's values, not an object.
The three container types compared
FormControl, FormGroup and FormArray all extend AbstractControl. They share the same properties (value, valid, errors, dirty, touched, valueChanges) and the same methods (setValidators, markAsTouched, disable). Because of this, any of them can be a child of a group or an array.
| Type | Holds | Children identified by | Shape changes at runtime | `value` type |
|---|---|---|---|---|
| `FormControl` | One value | Not applicable | No | The value itself |
| `FormGroup` | Named child controls | String key | Possible, but unusual | Object |
| `FormArray` | Ordered child controls | Numeric index | Yes, by design | Array |
The choice comes down to how you refer to the children. If you can name each field in the code (form.controls.email), use a group. If the code has to treat the children as "however many there are", use an array.
Creating and changing a FormArray
The constructor takes an array of controls. Here is a list of email addresses:
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]', '']Trace the list to see what each call does:
- After construction, the array is
['[email protected]']. pushappends, giving['[email protected]', ''].insert(0, ...)puts a control at index 0 and shifts the others right, giving['[email protected]', '[email protected]', ''].removeAt(1)removes the control at index 1, which is[email protected], giving['[email protected]', ''].
Indexes shift after every insert or remove. Never store an index and use it later without checking that the list has not changed.
The other members you will use often:
at(i)returns the control at indexi. In recent Angular versions it returnsundefinedfor an out-of-range index in typed code only if you opt in, so checklengthfirst.controlsis the underlying array of children. You loop over it in templates.lengthis the number of children.clear()removes every child.setControl(i, control)replaces the child at an index.
Every one of these methods that changes the list also recalculates the array's validity and emits valueChanges. You can pass { emitEvent: false } to push, insert, removeAt and clear to suppress that, which is useful when you add many controls in a loop.
How the parent aggregates its children
An array does not store a value of its own. It computes value from its children each time they change, and it computes its status the same way.
valueis an array of child values, in order. Disabled children are left out ofvalue. UsegetRawValue()when you need them included.validis true only if every enabled child is valid and the array's own validators pass.dirtyandtouchedbecome true when any child becomes so.errorsholds only errors from validators attached to the array itself. A child's errors stay on that child, and the array simply reportsinvalid.
This is why you can put one [disabled]="form.invalid" on a submit button and have it react to a single bad row deep in a list.
Arrays of controls and arrays of groups
An array can hold plain controls, as in the email example, or groups. Use controls when each row is one value, such as a tag, an email or a phone number. Use groups when each row has several related fields, such as an order line with a name and a quantity. The array's value then becomes an array of objects.
The type signature tells you which you have. FormArray<FormControl<string>> is a list of strings. FormArray<FormGroup<{ name: FormControl<string>; quantity: FormControl<number> }>> is a list of objects. A later chapter covers building and binding the second kind.
All children of an array should have the same type. Angular does not enforce this at runtime, but typed forms assume it, and a template that loops over mixed children will be hard to write correctly.
Setting values on a FormArray
Reading is easy. Writing is where people get caught.
setValue(values)requires an array with exactly the same length as the current list. If the lengths differ, it throws.patchValue(values)updates the children that exist. Extra values beyond the current length are ignored, with no error.reset(values)behaves likepatchValuefor the structure. It also clears the touched and dirty state.
None of these create controls. If the array has two children and you patch it with five values, you get two updated children and no new ones. To load data of unknown length, rebuild the list: call clear(), then push one control per record. A later chapter covers this in detail.
import { FormArray, FormControl } from '@angular/forms';
const tags = new FormArray([new FormControl('x', { nonNullable: true })]);
tags.patchValue(['a', 'b', 'c']);
console.log(tags.value); // ['a'], because only one control exists
try {
tags.setValue(['a', 'b', 'c']);
} catch (e) {
console.log('setValue throws when the length does not match');
}When to choose a FormArray
Use a FormArray when all of these are true:
- The user decides how many entries there are, or the server does.
- The entries are the same kind of thing, with the same fields and the same validation.
- Order matters, or you identify an entry by its position.
Typical cases are a list of email addresses, a shopping cart, a set of skills, the lines of an invoice, or the questions of a survey.
Choose something else in these cases:
- A fixed set of known fields. Use a
FormGroup. Named keys are easier to read and type-check thanarray.at(2). - A single field with many selected options, such as a group of checkboxes where the user ticks some. A
FormArrayof booleans works, but a singleFormControl<string[]>with a multi-select component is often simpler. - Records that need a stable key, such as rows you must match to server ids. A
FormGroupkeyed by id or aFormArrayof groups with anidfield both work. A bare array of strings does not. - Very large lists that the user never edits. Reactive forms create an object per control. For read-only display, plain data with a template loop is cheaper.
Common errors
- Using a group's tools on an array.
emails.get('0')works, butemails.controls.firstdoes not exist. Useat(0). - Expecting
patchValueto grow the list. It never does. Build the controls first. - Sharing one control instance between two arrays or two positions. A control can have only one parent. Create a fresh control for each entry, usually with a small factory function.
- Leaving stale indexes in event handlers. After
removeAt, every later row has a new index. Re-read the index from the loop, not from a variable captured earlier. - Reading
valuewhen you need disabled rows. UsegetRawValue()for those.
Exercise
A FormArray named phones holds three enabled FormControls: '111', '222' and '333'. You call phones.at(1).disable(), then phones.removeAt(0). What are phones.length and phones.value now?
Show answer
phones.length is 2, and phones.value is []. After removeAt(0), the remaining controls are '222' (disabled) and '333'. Disabled controls are left out of value, so value is ['333']. The correct answer is phones.value is ['333']. Length counts all children, so it is 2, while value has one entry.
Exercise
A FormArray has two controls. You call patchValue(['a', 'b', 'c']), then setValue(['a', 'b', 'c']). What happens in each case, and how do you load three values correctly?
Show answer
patchValue updates the two existing controls with 'a' and 'b' and ignores 'c', with no error. setValue throws because the array has two controls and you supplied three values. To load three values, call clear() and then push a new FormControl for each value.