My account

Forms in Angular

A reactive form is a tree of controls in your TypeScript code. Each control has a value, a status and flags like touched and dirty. Validators decide the status, async validators ask the server, and the template only shows errors at the right time. With typed forms, the compiler knows the shape of the value you send.

Not reviewedWritten with AI helpReading time: 15 minOnline shop exampleAngular 20 code

Author: bezzad

Contents

The problem: a checkout form that annoys people

Our shop has a checkout form: name, email, address and a coupon code. Customers complain:

  1. Red errors show at once, before they type anything.
  2. The coupon check is slow. Every key press sends a request to the server.
  3. They can press “Pay” twice, and sometimes the order is sent with an empty city.

All three come from how the form is built. Let us build it the right way.

Reactive or template-driven?

Angular has two kinds of forms:

  1. Template-driven forms use ngModel in the template. They are fine for a small form with two or three fields.
  2. Reactive forms build the form in TypeScript. The template only connects inputs to controls. They are easier to test, to change at run time, and they are fully typed.

For real business forms, like checkout, interviewers expect reactive forms. Angular 21 also has signal forms as an experimental API. Know that they exist, but most production code today uses reactive forms.

A form is a tree of controls

checkout formINVALIDnameVALIDemailVALIDcouponVALIDaddress groupINVALIDcityVALIDpostcodepatternOne invalid child makesevery parent invalid.
A FormGroup holds controls and other groups. Its status comes from its children: if one child is invalid, the group and the whole form are invalid.
import { Component, inject } from '@angular/core';
import {
  NonNullableFormBuilder, ReactiveFormsModule, Validators,
} from '@angular/forms';

@Component({
  selector: 'app-checkout',
  imports: [ReactiveFormsModule],
  templateUrl: './checkout.html',
})
export class Checkout {
  private fb = inject(NonNullableFormBuilder);

  form = this.fb.group({
    name: ['', Validators.required],
    email: ['', [Validators.required, Validators.email]],
    address: this.fb.group({
      city: ['', Validators.required],
      postcode: ['', Validators.pattern(/^\d{5}$/)],
    }),
    coupon: [''],
  });
}
  1. FormControl holds one value. FormGroup holds named children. FormArray holds a list, for example many gift messages.
  2. NonNullableFormBuilder makes controls that go back to their first value on reset, not to null. So the type of name is string, not string or null.
  3. Typed forms: the type of form.value is known. If you write form.value.adress with a typo, the compiler stops you.
  4. form.value skips disabled controls. form.getRawValue() includes them. Use getRawValue when you send the whole object.

Connecting the template

<form [formGroup]="form" (ngSubmit)="pay()">
  <label for="email">Email</label>
  <input id="email" type="email" formControlName="email" />
  @if (form.controls.email.touched
       && form.controls.email.hasError('email')) {
    <p class="error">Please write a valid email.</p>
  }

  <fieldset formGroupName="address">
    <label for="city">City</label>
    <input id="city" formControlName="city" />
  </fieldset>

  <button type="submit" [disabled]="saving()">Pay</button>
</form>
  1. formGroup connects the form element to the group. formControlName connects one input to one control by name.
  2. Show an error only after touched. A control is touched when the user leaves the field (blur). So the user is not shouted at before they start.
  3. Labels with for and id are still needed. A form is not accessible without them.

Control states

pristine → dirtyuntouched → touchedstatusthe user changed the valuethe user left the fieldresult of the validatorsvalue changessync validatorspassPENDINGVALID orINVALIDfailINVALIDAsync validators wait for the server.A new value cancels the old check.
Every control has three pairs of flags. Value changes run the sync validators first. Only if they pass, the async validators run and the status is PENDING until they answer.
  1. pristine / dirty: has the user changed the value?
  2. untouched / touched: has the user left the field?
  3. valid / invalid / pending / disabled: the result of the validators.

Validators

A validator is a function. It gets a control and returns null when all is fine, or an error object.

import { AbstractControl, ValidatorFn } from '@angular/forms';

// Cross-field: put it on the group, not on one control.
export const sameEmail: ValidatorFn = (group: AbstractControl) => {
  const email = group.get('email')?.value;
  const again = group.get('emailAgain')?.value;
  return email === again ? null : { emailMismatch: true };
};
  1. Put a cross-field validator on the group that holds both fields. A validator on one control does not run when the other field changes.
  2. Keep validators pure and fast. They run on every value change.

Async validators: ask the server

import { inject } from '@angular/core';
import { AsyncValidatorFn } from '@angular/forms';
import { catchError, map, of, switchMap, timer } from 'rxjs';

export function couponValidator(): AsyncValidatorFn {
  const api = inject(CouponApi); // call it in an injection context
  return (control) =>
    timer(400).pipe(                 // wait until typing stops
      switchMap(() => api.check(control.value)),
      map((ok) => (ok ? null : { badCoupon: true })),
      catchError(() => of(null)),     // server down: do not block
    );
}

coupon = this.fb.control('', {
  asyncValidators: [couponValidator()],
  updateOn: 'blur',
});
  1. When the value changes, Angular cancels the last async check and starts a new one. With timer, a request is only sent after 400 ms of no typing.
  2. updateOn: ‘blur’ updates the value and runs the validators only when the user leaves the field. Good for checks that need the server.
  3. Async validators run only when the sync validators pass. While they wait, the status is PENDING. Do not allow submit while pending.

Submitting safely

saving = signal(false);

pay() {
  if (this.form.invalid || this.form.pending) {
    this.form.markAllAsTouched(); // now every error shows
    return;
  }
  this.saving.set(true);
  this.orders.create(this.form.getRawValue()).subscribe({
    next: () => this.router.navigate(['/thanks']),
    error: () => this.saving.set(false),
  });
}
  1. markAllAsTouched shows every error when the user presses Pay too early.
  2. The saving signal disables the button, so a double click does not send two orders.
  3. The server must check again. Client validation is only for a better experience, it is not security.

Custom inputs: ControlValueAccessor

Our shop has a quantity stepper with minus and plus buttons. To use it with formControlName, the component implements ControlValueAccessor. It has four methods: writeValue (the form gives a value), registerOnChange (call it when the user changes the value), registerOnTouched (call it on blur), and setDisabledState. Then the component is registered with the NG_VALUE_ACCESSOR provider. After that, the stepper works like any input: validators, touched, reset.

Common mistakes

Mistake Result Better way
Showing errors when the control is invalid Red text before the user types. Show after touched, or after submit.
An async validator with no wait One request per key press. timer plus switchMap, or updateOn blur.
Cross-field check on one control It does not run when the other field changes. A validator on the group.
Submit with no saving flag Two orders on a double click. Disable while saving, and while pending.
Using form.value with disabled fields Disabled values are missing. getRawValue.
Trusting client validation Bad data from scripts and old apps. Validate again on the server.

Summary in 6 lines

  1. Use typed reactive forms for real forms. The form is a tree of controls in TypeScript.
  2. Each control has a value, a status, and the touched and dirty flags.
  3. Show errors after touched or after submit, not at once.
  4. Put cross-field validators on the group. Keep validators pure and fast.
  5. Async validators run after the sync ones pass. Wait with timer or use updateOn blur.
  6. On submit: markAllAsTouched, block while pending or saving, and validate again on the server.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.