Reactive Forms — Angular

A reactive form is a form whose rules are built in the class: new FormGroup({ phone: new FormControl('', [Validators.required…

A delivery form that accepts anything causes trouble. An empty name, a phone number that's only 07700, a quantity of 0. The order comes in, and the courier has no idea who to call.

A reactive form stops wrong orders before they are sent. In a reactive form, the form's rules are built in the class. Each input field is represented by one FormControl object (called a control), and all the controls are gathered in one FormGroup. The template only connects each <input> to its control. Picture the delivery order form at Jali's Pancake Stall. The customer fills in the paper form. But the cashier holds a rule book of their own: the name is required, the phone number starts with 07, the quantity is at least 1. Every time the customer writes in a field, the cashier checks that field right away and knows whether the form is valid (meets every rule) yet. In Angular, the paper form is the template, and the cashier's rule book is the FormGroup with its rules in the class.

FormGroup and FormControl

This is the order form of Jali's Pancake Stall, as a reactive form:

import { Component } from '@angular/core'
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms'

@Component({
  selector: 'app-order',
  standalone: true,
  imports: [ReactiveFormsModule],
  template: `
    <form [formGroup]="orderForm" (ngSubmit)="send()">
      <input formControlName="name" placeholder="Name" />
      @if (name.touched && name.errors?.['required']) {
        <p class="error">Name is required.</p>
      }
      <input formControlName="phone" placeholder="Phone number" />
      @if (phone.touched && phone.errors?.['required']) {
        <p class="error">Phone number is required.</p>
      }
      @if (phone.touched && phone.errors?.['pattern']) {
        <p class="error">The phone number starts with 07, 11 digits in all.</p>
      }
      <input formControlName="quantity" type="number" />
      @if (quantity.touched && quantity.errors) {
        <p class="error">Quantity must be at least 1.</p>
      }
      <button type="submit" [disabled]="orderForm.invalid">Send</button>
    </form>
  `,
})
export class Order {
  orderForm = new FormGroup({
    name: new FormControl('', Validators.required),
    phone: new FormControl('', [Validators.required, Validators.pattern('07[0-9]{9}')]),
    quantity: new FormControl(1, [Validators.required, Validators.min(1)]),
  })

  get name() { return this.orderForm.controls.name }
  get phone() { return this.orderForm.controls.phone }
  get quantity() { return this.orderForm.controls.quantity }

  constructor() {
    this.orderForm.valueChanges.subscribe((value) => console.log('valueChanges:', JSON.stringify(value)))
  }

  send() {
    console.log('sent:', JSON.stringify(this.orderForm.value))
  }
}

Validators: each field's rules

Validators holds Angular's built-in validators. When a rule fails, the control's errors records that rule. Here are some of the built-in validators:

Validator Fails when Contents of errors
Validators.required empty ('' or null) { required: true }
Validators.min(1) the number is below 1 { min: { min: 1, actual: 0 } }
Validators.pattern('07[0-9]{9}') not 07 followed by 9 digits { pattern: { requiredPattern: '^07[0-9]{9}$', actualValue: '07700' } }
Validators.minLength(8) fewer than 8 characters { minlength: { requiredLength: 8, actualLength: 3 } }
Validators.email not shaped like an email address { email: true }

07[0-9]{9} is a regex, a text pattern: 07, then [0-9] (one digit) 9 times. The phone field from empty to correct:

Phone field contents phone.errors orderForm.status (name and quantity already correct)
(empty) { required: true } INVALID
07700 { pattern: { ... } } INVALID
07700900123 null VALID

When to show an error message

errors is filled in from the moment the form is created. The empty phone field has { required: true } from the very first second. So if the message "Phone number is required." is guarded only by @if (phone.errors), it shows as soon as the form opens, before the customer touches anything. The customer gets scolded before they had a chance to type.

That's why the message should wait until the customer leaves the field. Each control has a few states you can read:

State Becomes true when
touched the field has been left (focus moved elsewhere)
dirty the customer has changed its value
invalid errors isn't null

@if (phone.touched && phone.errors?.['pattern']) only shows its message after the customer types 07700 and moves to another field. errors?.['pattern'] checks whether the pattern rule is the one that failed, so each rule can have its own sentence. (?. prevents an error when errors is null.)

The Send button and valueChanges

The rules live in TypeScript, so they're easy to test

Every rule and value of the form lives in the class, not in the template. So the form can be checked without any page at all. In this example, setValue('07700') fills in the phone field through code, not by typing:

const form = new FormGroup({
  phone: new FormControl('', [Validators.required, Validators.pattern('07[0-9]{9}')]),
})
form.controls.phone.setValue('07700')
console.log(form.valid) // false

The main advantage of reactive forms over template-driven forms (forms whose rules are written in the template, the next lesson) is this: the logic is in TypeScript, so it can be unit tested (tested in small pieces) without the DOM.

The first exercise uses the same shape: loginForm = new FormGroup({ email: new FormControl('', [Validators.required]), password: new FormControl('', [Validators.required]) }), <form [formGroup]="loginForm">, two <input formControlName> and a Login button. The second exercise adds Validators.email and Validators.minLength(8), plus [disabled]="regForm.invalid".

A third option: Signal Forms, stable since Angular 22. The data is kept in one signal, and the rules are written as functions inside form(). This is the same order form, but its template only has the phone field:

import { Component, signal } from '@angular/core'
import { FormField, form, pattern, required } from '@angular/forms/signals'

@Component({
  selector: 'app-order',
  imports: [FormField],
  template: `
    <input [formField]="orderForm.phone" placeholder="Phone number" />
    @if (orderForm.phone().touched() && orderForm.phone().invalid()) {
      <p class="error">{{ orderForm.phone().errors()[0].message }}</p>
    }
    <button [disabled]="orderForm().invalid()">Send</button>
  `,
})
export class Order {
  order = signal({ name: '', phone: '', quantity: 1 })
  orderForm = form(this.order, (o) => {
    required(o.name)
    required(o.phone, { message: 'Phone number is required.' })
    pattern(o.phone, /^07[0-9]{9}$/, { message: 'The phone number starts with 07, 11 digits in all.' })
  })
}

In Signal Forms, you also read a field's state by calling it, like a signal: orderForm.phone().touched(). Tried on Angular 22.2: type 07700 and leave the field, and the pattern message appears. At that moment order() already holds "phone":"07700". The Send button stays off while name is still empty, because of required(o.name).

Way When to pick it
Reactive form (this lesson) Projects that already use it, or when you need valueChanges and RxJS. The exercises use this way.
Template-driven (ngModel) Small forms with one or two fields.
Signal Forms (form()) New apps that already use signals, as the Angular docs advise.

📌 FormBuilder and reset

FormBuilder is a service that writes the same group more briefly: private fb = inject(FormBuilder), then orderForm = this.fb.group({ name: ['', Validators.required], ... }). Be careful with orderForm.reset(), which clears the form: every value becomes null, not its initial value. So value holds {"name":null,"phone":null,"quantity":null}. Use this.fb.nonNullable.group(...) so that reset() goes back to the initial values.

⚠️ A form that isn't connected, or complains too early

TL;DR: A reactive form is a form whose rules are built in the class: new FormGroup({ phone: new FormControl('', [Validators.required, Validators.pattern('07[0-9]{9}')]) }). FormGroup is one form, FormControl (a control) one field, and Validators the field's rules. The template connects them with [formGroup]="orderForm" and formControlName="phone", plus ReactiveFormsModule in imports. Each control has errors (the failing rules, or null when it passes), touched (the field has been left) and dirty (its value has been changed). errors is already filled in when the form opens, so show messages with @if (phone.touched && phone.errors?.['pattern']). [disabled]="orderForm.invalid" turns the Send button off while something is wrong, (ngSubmit) runs send(), and valueChanges (an Observable) sends the form's value every time it changes. Because the logic is in TypeScript, the form can be tested without the DOM.

⚡ The rules are built in the class

Write:

orderForm = new FormGroup({
  name: new FormControl('', Validators.required),
  phone: new FormControl('', [Validators.required, Validators.pattern('07[0-9]{9}')]),
})
// template: <form [formGroup]="orderForm"> <input formControlName="phone" />

Meaning: In a reactive form (a form whose rules are built in the class), each field becomes a FormControl (a control) with its rules. Examples are Validators.required (must be filled in) and Validators.pattern(...) (must match the pattern: 07, then 9 digits). All the controls are gathered in a FormGroup, one form. The template only connects: [formGroup] on the <form>, formControlName on each <input>, and ReactiveFormsModule goes in imports.

In the exercise, the grader checks for [formGroup]= in the template, Validators.required, and a formControlName on every <input> inside the <form>.

⚡ Error messages wait for touched

Write:

@if (phone.touched && phone.errors?.['pattern']) {
  <p class="error">The phone number starts with 07, 11 digits in all.</p>
}
Guess first: phone.errors holds the rules that failed, and an empty phone field fails Validators.required. With only @if (phone.errors), when does "Phone number is required." show?

As soon as the form opens, before the customer touches anything. errors is filled in from the moment the form is created.

Meaning: phone is the phone number field's control. touched only becomes true after the field is left, so the message waits until the customer has finished with that field. errors?.['pattern'] checks only the pattern rule, so this message only shows for a number in the wrong shape.

⚡ Logic in TypeScript, so it's easy to test

Write:

const form = new FormGroup({
  phone: new FormControl('', [Validators.required, Validators.pattern('07[0-9]{9}')]),
})
form.controls.phone.setValue('07700')
console.log(form.valid) // false

Meaning: setValue('07700') fills in the phone field from code, and form.valid is false because 07700 doesn't match the pattern. The main advantage of reactive forms over template-driven forms (forms whose rules are written in the template) is this: the logic is in TypeScript, so it can be tested without the DOM. On the page, [disabled]="orderForm.invalid" turns the Send button off while anything is wrong.

What you will learn