Sub topic 2
FormControl and FormGroup in brief
This chapter assumes you know TypeScript, can write a standalone Angular component, and have seen FormControl, FormGroup and Validators once before. It is a focused recap of the two building blocks that FormArray extends. The next chapters rely on the details here, especially nullability, disabled controls, and how validity propagates upward.
The shared base: AbstractControl
FormControl, FormGroup and FormArray all extend AbstractControl. Each one exposes the same core members: value, status, valid, errors, dirty, touched, parent, valueChanges and methods such as setValue, reset, disable and markAsTouched. A group or array holds other controls, so the controls form a tree. A FormControl is always a leaf.
| Class | Holds | Value type | Shape known at compile time |
|---|---|---|---|
| `FormControl<T>` | One value | `T` | Not applicable |
| `FormGroup` | Named child controls | Object keyed by control name | Yes, the keys are fixed |
| `FormArray` | Ordered child controls | Array | No, the length changes at runtime |
The last row is why FormArray exists. A group suits a fixed set of named fields, such as name and email. It does not suit "any number of email addresses".
FormControl
A FormControl tracks the value and the validation state of one input.
import { FormControl, Validators } from '@angular/forms';
const email = new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.email],
});
console.log(email.value); // ''
console.log(email.valid); // false, because required fails on an empty string
console.log(email.errors); // { required: true }
email.setValue('[email protected]');
console.log(email.valid); // true
email.reset();
console.log(email.value); // '' because reset returns to the initial valueWhy nonNullable matters
By default, new FormControl('') has the type FormControl<string | null>. Calling reset() sets the value to null, so every read has to handle null. With nonNullable: true, the type is FormControl<string> and reset() restores the initial value instead. The rest of this tutorial uses nonNullable controls, either explicitly or through NonNullableFormBuilder.
Status values
A control's status is one of four strings:
VALID: all validators pass.INVALID: at least one validator fails.PENDING: an async validator is still running.DISABLED: the control is excluded from validation and, as described below, from its parent'svalue.
FormGroup
A FormGroup aggregates named child controls. Its value is an object with one key per child, and its status is derived from its children.
import { FormControl, FormGroup, Validators } from '@angular/forms';
const profile = new FormGroup({
name: new FormControl('', { nonNullable: true, validators: Validators.required }),
email: new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.email],
}),
nickname: new FormControl('', { nonNullable: true }),
});
console.log(profile.status); // 'INVALID'
profile.setValue({ name: 'Ada', email: '[email protected]', nickname: 'ada' });
console.log(profile.status); // 'VALID'
console.log(profile.controls.name.value); // 'Ada'Validity bubbles up
A group is VALID only when every enabled child is valid. When one child changes, Angular recalculates the status of each ancestor. The same rule applies to a FormArray, so one invalid entry in a list makes the whole form invalid.
value versus getRawValue
group.value leaves out disabled controls. group.getRawValue() includes them.
profile.controls.nickname.disable();
console.log(profile.value);
// { name: 'Ada', email: '[email protected]' }
console.log(profile.getRawValue());
// { name: 'Ada', email: '[email protected]', nickname: 'ada' }This is a common source of "my field is missing from the payload" bugs. If a field is disabled in the UI but you still need to send it, read getRawValue(). The same distinction applies to FormArray, where a later chapter returns to it.
setValue and patchValue
setValue requires a value for every key in the group. It throws if you omit one or add an unknown one. patchValue accepts a partial object and ignores keys it does not know.
profile.patchValue({ name: 'Grace' }); // fine, updates only name
// Throws: the keys email and nickname are missing
// profile.setValue({ name: 'Grace' });Use setValue when a missing key would be a bug you want to catch. Use patchValue for partial updates.
Changing the shape at runtime
A group can gain or lose controls with addControl, removeControl and setControl. Each call recomputes validity.
profile.addControl('phone', new FormControl('', { nonNullable: true }));
profile.removeControl('phone');Typed groups restrict these methods. To add a control the type does not already know about, declare it as optional in the type, or use a FormArray when the number of entries is what varies.
Creating groups with NonNullableFormBuilder
NonNullableFormBuilder produces nonNullable controls without repeating the option on every field. Each key takes either a plain initial value or a [value, validators] pair.
import { Component, inject } from '@angular/core';
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
@Component({
selector: 'app-profile-form',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form" (ngSubmit)="save()">
<input formControlName="name" placeholder="Name" />
<input formControlName="email" placeholder="Email" />
@if (form.controls.email.touched && form.controls.email.errors; as errors) {
<p>{{ errors['required'] ? 'Email is required' : 'Email is not valid' }}</p>
}
<button type="submit" [disabled]="form.invalid">Save</button>
</form>
`,
})
export class ProfileFormComponent {
private fb = inject(NonNullableFormBuilder);
form = this.fb.group({
name: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
});
save() {
console.log(this.form.getRawValue());
}
}The template shows the binding pattern. [formGroup] connects the form element to a group, and formControlName connects each input to a child by key name. In the next chapters you will use formArrayName and [formGroupName] for the same purpose inside arrays.
Typed access
Since Angular 14, forms are typed. form.controls.email has type FormControl<string>, and form.getRawValue() returns { name: string; email: string }. A misspelled key such as form.controls.emial is a compile error rather than a runtime undefined.
form.value has the type Partial<{ name: string; email: string }> because any control could be disabled. Prefer getRawValue() when you want a fully typed object and know the controls are enabled, or when you want disabled values included.
Common mistakes
- Using nullable controls by accident.
new FormControl('')producesstring | null. AddnonNullable: true, or build the form withNonNullableFormBuilder. - Reading
valuewhen a control is disabled. The disabled control's key is absent. UsegetRawValue()when that matters. - Calling
setValuewith a partial object. It throws at runtime. UsepatchValue. - Using a group for a list. If you find yourself generating keys such as
email1,email2andemail3, you need aFormArray. Groups are for fixed named fields. - Forgetting to re-check validity after changing shape.
addControlandremoveControlupdate validity for you, but only if you use them. Changingcontrolsdirectly bypasses that recalculation.
How this connects to FormArray
A FormArray behaves like a FormGroup whose children are addressed by position instead of by name. Validity bubbles up in the same way. value is an array instead of an object, and disabled children are omitted from it in the same way. Because the array can be changed at runtime, each child can itself be a FormControl or a whole FormGroup, such as a name and quantity pair. The next chapter builds on this.
Exercise
A form group has the controls title and status. The status control is disabled. You call form.value and send the result to a server, and the server complains that status is missing. What is the cause, and which call gives you an object that includes status?
Show answer
FormGroup.value leaves out disabled controls, so status is not in the object. Call form.getRawValue(), which includes the values of disabled controls. Alternatively, enable the control before reading the value, but getRawValue() is simpler.
Exercise
You write const c = new FormControl('draft'); c.setValue('final'); c.reset();. What are the type of c and the value of c.value after the reset() call? How would you change the declaration so that reset() returns the control to 'draft'?
Show answer
The type is FormControl<string | null>, and after reset() the value is null. Declare the control with new FormControl('draft', { nonNullable: true }). The type becomes FormControl<string>, and reset() restores the initial value 'draft'.