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 FormControl, FormGroup and Validators. It also assumes you can import ReactiveFormsModule into a standalone component.
The working model
A FormArray is a form control that holds an ordered list of child controls. The children can be FormControl, FormGroup or other FormArray instances. You address each child by its numeric index, and you can add or remove children while the form is running.
FormGroup and FormArray both aggregate child controls, but they differ in how they identify them:
| Feature | FormGroup | FormArray |
|---|---|---|
| Children identified by | Key name | Numeric index |
| Number of children | Fixed by your code | Changes at runtime |
| `value` is | An object | An array |
| Typical use | Known fields, such as name and email | A list, such as email addresses or order lines |
Like every aggregate control, a FormArray computes its status from its children. It is invalid if any child is invalid. It is dirty if any child is dirty. It is touched if any child is touched.
A first example
This code builds a FormArray of email controls and changes it at runtime.
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);Here is what happens step by step:
- The array starts with one control,
[email protected]. pushappends an empty control to the end, so the length is 2.insert(0, ...)places a new control at index 0 and shifts the others up. The order is now[email protected],[email protected], and the empty control.removeAt(1)removes[email protected].
The code prints 2, then ['[email protected]', '']. The value of a FormArray is a plain array of the child values, in order.
The nonNullable: true option makes each control reset to its initial value instead of null. This keeps the control's type as string instead of string | null.
When to choose FormArray
Use a FormArray when the number of inputs is not known when you write the code. Common cases are:
- A list of email addresses, phone numbers or tags.
- Order lines, where each row has a name and a quantity.
- Answers to a quiz whose length comes from the server.
Use a FormGroup when the fields are fixed and each has its own meaning, such as firstName and lastName. If you find yourself generating key names like email1, email2 and email3, switch to a FormArray.
Common errors
- Reading by key.
emails.get('0')works, butemails.controls[0]oremails.at(0)is clearer and is typed. - Expecting an object.
form.value.emailsis an array. Code that treats it as an object with keys fails. - Assuming
resetrestores the length. Callingreset()clears the values of the existing controls. It does not add back controls you removed. - Mutating
controlsdirectly. Pushing ontoemails.controlsskips the array's update logic, so the value and validity can go stale. Usepush,insert,removeAtandclear.
The next chapters cover creating arrays with FormBuilder and binding them in a template.
Exercise
A form needs one field for a user's name and a variable number of phone number fields. Which control types would you use for each, and what is the value shape of the phone numbers?
Show answer
Use a FormControl (inside the parent FormGroup) for the name, because it is one fixed field. Use a FormArray of FormControls for the phone numbers, because their count changes at runtime. The FormArray's value is an array of strings, for example ['555-0100', '555-0101'].
Exercise
After running const a = new FormArray([new FormControl('x'), new FormControl('y')]); a.removeAt(0); a.push(new FormControl('z'));, what does a.value contain?
Show answer
['y', 'z']. Removing index 0 leaves 'y', and push appends 'z' at the end.