Sub topic 8
Reading and submitting the value
This chapter assumes you can build a FormArray of FormGroups, bind it with formArrayName and [formGroupName], and add or remove rows, as covered in the earlier chapters. Here you will learn what a FormArray exposes as its value, why value and getRawValue() can differ, and how to turn the form into a payload you can send to a server.
What the value of a FormArray looks like
A FormArray stores its value as a plain array. Each position holds the value of the control at the same index. For an array of groups, each position holds an object.
For the order form from the previous chapter, the form value has this shape:
// form.getRawValue()
{
items: [
{ name: 'Keyboard', quantity: 1 },
{ name: 'Mouse', quantity: 2 },
]
}The value is recalculated whenever a child control changes, and FormArray.length always matches the length of that array. An array with no controls has the value []. Treat the value as a read-only snapshot. Changing the returned array or its objects does not change the form. To change the form, call setValue, patchValue, push, removeAt or clear on the controls.
value versus getRawValue()
value leaves out disabled controls. getRawValue() includes every control, enabled or not.
import { FormArray, FormControl } from '@angular/forms';
const tags = new FormArray([
new FormControl('a', { nonNullable: true }),
new FormControl('b', { nonNullable: true }),
new FormControl('c', { nonNullable: true }),
]);
tags.at(1).disable();
console.log(tags.value); // ['a', 'c']
console.log(tags.getRawValue()); // ['a', 'b', 'c']In tags.value, 'c' sits at index 1 even though its control is at index 2. Indexes in value no longer line up with indexes in controls. If you use value and then look up a control by position, you can read or change the wrong row.
| Property | Disabled controls | Typed result | Typical use |
|---|---|---|---|
| `value` | Left out | Partial types on groups | Sending only the fields the user can edit |
| `getRawValue()` | Included | Full types | Reading everything, including locked fields |
The same rule applies to a FormGroup inside the array. A disabled group is dropped from the array's value. If every child of a group is disabled, the group counts as disabled too.
Why value is Partial in typed forms
With typed forms, form.value has optional properties. For the order form, TypeScript treats form.value.items as possibly undefined, and each entry's name and quantity as possibly undefined. The compiler allows for the case where those controls are disabled and missing.
getRawValue() has no such gap, so its type is complete:
const raw = this.form.getRawValue();
// raw.items is { name: string; quantity: number }[]
const total = raw.items.reduce((sum, item) => sum + item.quantity, 0);This only works when the controls are built with NonNullableFormBuilder (or nonNullable: true). Otherwise each value type includes null.
Submitting safely
A good submit handler does three things in order:
- Stop if the form is invalid, and mark every control as touched so the errors show.
- Read the value with
getRawValue()orvalue, depending on whether disabled fields belong in the payload. - Map the form shape to the shape your API expects.
Here is a complete component that does this:
import { Component, inject } from '@angular/core';
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
interface OrderLine {
name: string;
quantity: number;
}
@Component({
selector: 'app-order-form',
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="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">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());
}
removeItem(index: number) {
this.items.removeAt(index);
}
submit() {
if (this.form.invalid) {
this.form.markAllAsTouched();
return;
}
const lines: OrderLine[] = this.form
.getRawValue()
.items.map(({ name, quantity }) => ({ name: name.trim(), quantity }));
console.log(lines);
}
}markAllAsTouched() walks the whole tree, including every row in the array. This matters because error messages are usually shown only for touched controls. Without this call, a user who clicks Submit on an untouched form sees nothing happen.
In this version the Submit button is not disabled when the form is invalid. Disabling it hides the reason the form cannot be submitted. Leaving it enabled lets you show the errors on click. Either choice is valid, but pick one on purpose.
The submit flow
Pending validators
invalid is false while an async validator is still running. The form's status is PENDING in that case, not INVALID. If your rows use async validators, such as a check that an email is not already taken, test this.form.pending as well, or the user can submit before the check finishes.
if (this.form.invalid || this.form.pending) {
this.form.markAllAsTouched();
return;
}Reshaping the value for the API
The form's structure often differs from the API's. Common differences are:
- The API wants a flat list of strings, but the form uses groups.
- The API wants numbers, but the form holds strings, for example from
<input type="text">. - The API wants IDs for existing rows and no ID for new ones.
Do the conversion in one place, in the submit handler or a small mapping function. Do not let the form shape leak into your service layer. A mapping function is also easy to unit test without a component.
interface OrderLine {
name: string;
quantity: number;
}
export function toPayload(items: { name: string; quantity: number }[]): OrderLine[] {
return items
.map(({ name, quantity }) => ({ name: name.trim(), quantity }))
.filter((line) => line.name.length > 0);
}Resetting after a successful submit
form.reset() resets every control, and it keeps the number of rows. With NonNullableFormBuilder, each control returns to the initial value it was created with, not to null. In the order form, the first row goes back to an empty name and a quantity of 1, but any rows the user added are still there.
To return to a single blank row, clear the array and push a fresh group:
resetForm() {
this.items.clear();
this.items.push(this.createItem());
this.form.markAsPristine();
this.form.markAsUntouched();
}clear() removes all controls and updates the value. Pushing a new group restores the minimum number of rows, which matters if you validate that the array is not empty.
Common mistakes
- Reading
valuewhen some rows are locked. The locked rows vanish from the payload and the indexes shift. UsegetRawValue()when you want every row. - Mutating the snapshot. Changing
form.value.items[0].name = 'x'does nothing to the form. Usethis.items.at(0).patchValue({ name: 'x' }). - Sending the form value straight to the API. The form shape and the API shape drift apart over time. Map explicitly.
- Forgetting
type="button". Helper buttons then submit the form. - Checking only
invalid. Async validators leave the formPENDING.
Exercise
A FormArray named emails has three controls. The second control is disabled. What do emails.value and emails.getRawValue() return, and which one should you send to the server if the disabled field is a locked, pre-filled address that the server still needs?
Show answer
emails.value has two entries, because the disabled control is left out, and the later entries shift down by one index. emails.getRawValue() has all three entries. Send getRawValue(), because the server needs the locked address, and value would drop it.
Exercise
Your submit handler runs const { items } = this.form.value; and TypeScript reports that items is possibly undefined. Why does this happen, and what is the simplest fix that keeps the types accurate?
Show answer
In typed forms, FormGroup.value is a Partial type, because any child control might be disabled and therefore missing. The simplest fix is to call this.form.getRawValue(), which includes disabled controls and returns the full type, so items is defined. This assumes the controls were created as non-nullable.