Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 74 ยท Forms

Reactive Forms

Build typed Angular reactive forms with FormControl, FormGroup, FormArray and FormBuilder, read value and status, react to valueChanges and avoid the null-on-reset trap.

In template-driven forms the HTML template creates the form model for you. In reactive forms you create the model yourself, in TypeScript, and the template simply binds to it. That sounds like more work, and for a tiny form it is. But it pays back quickly: the form is a plain object you can inspect, test without rendering anything, build from configuration, validate with your own functions, and observe as a stream of changes.

This lesson introduces the building blocks (FormControl, FormGroup, FormArray), the FormBuilder shortcut, how to read value and status, how to react to changes with valueChanges, and how typed forms keep you honest. Validation gets its own lesson, Validation and Custom Validators.

The Angular code in this lesson is read-only, because the site can't run the Angular compiler. The runnable examples are stand-ins: a small control tree that behaves like the real one (values and status bubbling up, patchValue, disabled controls, valueChanges) and a typed-controls demo showing why nonNullable exists. They are not Angular's real classes.

The three building blocks

Everything in a reactive form is an AbstractControl, and there are three concrete kinds:

  • FormControl: one value, such as a single input.
  • FormGroup: a set of named controls, such as a whole form or an address section. Its value is an object.
  • FormArray: a list of controls, such as phone numbers the user can add and remove. Its value is an array.

Groups and arrays can contain groups and arrays, so you get a tree. Values and validity flow up the tree: a group is invalid if any child is, and its value is assembled from its children.

flowchart TD
  F["FormGroup: form<br/>value is an object"] --> N["FormControl: name"]
  F --> E["FormControl: email"]
  F --> A["FormGroup: address"]
  F --> P["FormArray: phones"]
  A --> C["FormControl: city"]
  P --> P1["FormControl [0]"]
  P --> P2["FormControl [1]"]

The form is a tree of controls; each group or array summarizes its children.

Creating a form

You can build controls with constructors, but FormBuilder is shorter. Inject it (as with any service) and import ReactiveFormsModule into the component:

TypeScript
import { Component, inject } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';

@Component({
  selector: 'app-profile',
  imports: [ReactiveFormsModule],
  templateUrl: './profile.component.html',
})
export class ProfileComponent {
  private readonly fb = inject(FormBuilder);

  readonly form = this.fb.nonNullable.group({
    name: ['', [Validators.required, Validators.minLength(2)]],
    email: ['', [Validators.required, Validators.email]],
    address: this.fb.nonNullable.group({
      city: [''],
      zip: [''],
    }),
    phones: this.fb.array([this.fb.nonNullable.control('')]),
  });

  get phones() {
    return this.form.controls.phones;
  }

  addPhone(): void {
    this.phones.push(this.fb.nonNullable.control(''));
  }

  removePhone(index: number): void {
    this.phones.removeAt(index);
  }

  submit(): void {
    if (this.form.invalid) {
      this.form.markAllAsTouched();
      return;
    }
    console.log(this.form.getRawValue());
  }
}

Each entry in group({...}) is [initialValue, validators]. Without the builder the same thing reads new FormGroup({ name: new FormControl('', { nonNullable: true, validators: [Validators.required] }) }).

Binding the template

The template connects DOM elements to controls with directives instead of ngModel:

HTML
<form [formGroup]="form" (ngSubmit)="submit()">
  <input formControlName="name" />
  <input formControlName="email" type="email" />

  <fieldset formGroupName="address">
    <input formControlName="city" />
    <input formControlName="zip" />
  </fieldset>

  <div formArrayName="phones">
    @for (phone of phones.controls; track $index) {
      <input [formControlName]="$index" />
      <button type="button" (click)="removePhone($index)">Remove</button>
    }
  </div>
  <button type="button" (click)="addPhone()">Add phone</button>

  <button type="submit">Save</button>
</form>

[formGroup] attaches the model to the <form>, formControlName links an input to a named child, formGroupName and formArrayName step into nested parts, and inside a formArrayName the control name is the index. Because the controls come from code, you can iterate over phones.controls with @for (control flow). Using track $index is fine for rows that are only added or removed at the end; if you reorder rows, track something stable instead.

Value and status

Every control exposes the same properties:

  • value: the current value (an object for a group, an array for an array).
  • status: 'VALID', 'INVALID', 'PENDING' (async validator running) or 'DISABLED'; plus the booleans valid, invalid, pending, disabled.
  • touched/dirty and their opposites, with the same meaning as in template-driven forms.
  • errors: null or an object of failed rules.

Two details trip up almost everyone:

  1. Disabled controls are left out of form.value. If you disable name, form.value has no name key. Use form.getRawValue() when you need every control, disabled or not.
  2. A disabled control isn't validated, so it doesn't make its group invalid either.

To change values from code, use setValue (every key required, throws if one is missing) or patchValue (any subset), and reset() to return to the initial values and clear touched and dirty.

TypeScript
this.form.patchValue({ name: 'Ada', address: { city: 'London' } });
this.form.controls.name.disable();
this.form.reset();

A runnable control tree

The stand-in below implements a small version of the tree: controls hold values, groups and arrays combine them, status considers disabled controls, patchValue and reset work like the real ones, and every change notifies listeners up the tree.

TypeScript Stand-in: a form model with a control tree

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Look at what each step prints. Typing a name makes the name control valid but the form is still invalid because email is empty; patching the email makes the whole tree valid; the disabled name disappears from value but stays in the raw value; and reset() returns every control to its initial value and invalidates the form again. (In real Angular, reset() on a control created without nonNullable sets the value to null, not to its initial value. The next section explains why that matters.)

Typed forms and nonNullable

Since Angular 14, forms are typed. new FormControl('') has the type FormControl<string | null>, because calling control.reset() sets a plain control to null. That's accurate, but it means form.value.name is string | null | undefined (the undefined comes from possibly-disabled controls) and you must handle it everywhere.

The usual fix is nonNullable: new FormControl('', { nonNullable: true }), or all controls at once with fb.nonNullable.group(...). A non-nullable control resets to its initial value and has the type FormControl<string>. Use nullable controls only when "empty" really should be null, for example an optional number input.

Typed forms also give you autocompletion: form.controls.address.controls.city is known to exist, and a typo is a compile error. The stand-in below mimics the type machinery with overloads. A control created without the option has a T | null type and goes to null on reset; with nonNullable it keeps T and resets to the initial value. A helper builds the typed value object of a whole group.

TypeScript Stand-in: nullable and non-nullable typed controls

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Calling .toUpperCase() directly on loose.value would not compile, because it can be null. The compiler is nudging you toward the same decision real forms ask for. The last two lines show how a typed group value lets value.email be used as a string with no checks, while age stays number | null.

Reacting to changes

Controls expose valueChanges and statusChanges as RxJS observables (see RxJS essentials). They emit whenever the value or status changes, which makes live behavior simple:

TypeScript
import { DestroyRef, inject } from '@angular/core';
import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
import { debounceTime, distinctUntilChanged } from 'rxjs';

// inside the component class
private readonly destroyRef = inject(DestroyRef);

readonly search = this.fb.nonNullable.control('');

constructor() {
  this.search.valueChanges
    .pipe(debounceTime(300), distinctUntilChanged(), takeUntilDestroyed(this.destroyRef))
    .subscribe((term) => this.load(term));
}

// or expose the whole form's value as a signal
readonly formValue = toSignal(this.form.valueChanges, { initialValue: this.form.getRawValue() });

Always end the subscription when the component is destroyed (takeUntilDestroyed), or it will leak. Operators like debounceTime are the subject of RxJS operators, and toSignal is covered in Signals and RxJS interop.

Template-driven or reactive?

Template-driven Reactive
Model lives in the template TypeScript
Setup FormsModule, ngModel ReactiveFormsModule, FormBuilder
Dynamic fields awkward natural (FormArray, code)
Custom validation directives plain functions
Testing needs the template test the model alone
Best for small, static forms everything else

Most production codebases pick reactive forms as their default, so that every form looks the same.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the value of a FormArray?

    A FormGroup's value is an object, a FormArray's value is an array, and a FormControl's value is a single value.
  2. 2. You disable the "name" control. What does form.value contain?

    Disabled controls are excluded from value (and from validation). getRawValue includes them.
  3. 3. Why is new FormControl('') typed as FormControl<string | null>?

    reset() on a control without nonNullable goes to null, so the type has to allow it. With { nonNullable: true } it resets to the initial value and is typed as string.
  4. 4. What is the difference between setValue and patchValue on a group?

    setValue must match the full shape of the group and throws if a key is missing. patchValue updates only the keys you pass.
  5. 5. How should you stop a valueChanges subscription when the component is destroyed?

    Form observables live as long as the control, so you must unsubscribe yourself. takeUntilDestroyed ties the subscription to the component's lifetime.

Summary

  • Reactive forms define the model in TypeScript: FormControl (one value), FormGroup (object) and FormArray (list), nested into a tree where value and validity bubble up.
  • FormBuilder (especially fb.nonNullable.group) shortens the setup; bind with [formGroup], formControlName, formGroupName and formArrayName.
  • Read value, status, errors, touched and dirty; disabled controls are excluded from value and from validation, and getRawValue() includes them.
  • setValue needs the full shape, patchValue accepts a subset, and reset() restores initial values and clears touched and dirty.
  • Forms are typed; plain controls are T | null because reset() produces null, so use nonNullable unless null is meaningful.
  • valueChanges and statusChanges are observables; limit them with takeUntilDestroyed and operators such as debounceTime.
  • The Angular code here is read-only; the control tree and typed controls are stand-ins.

Next: Validation and Custom Validators