Reactive Forms

Reactive Forms in Angular: Picture the declaration desk at an international arrivals hall. Each traveler fills out a structured packet - name, passport number,…

The Analogy: A Customs Declaration Desk

Picture the declaration desk at an international arrivals hall. Each traveler fills out a structured packet - name, passport number, goods to declare - and hands it to the desk. That packet is a FormGroup: a single named document made of individual fields. Behind the counter, each field has its own inspector who stamps it VALID or INVALID against a rule - this box is required, that one must look like a passport number. Each field with its inspectors is a FormControl plus its validators. Crucially, the authoritative record lives in the office system; the paper in the traveler's hand is just a synced copy of what the office already holds. That is what "model-driven" means - the form model, not the DOM input, is the source of truth.

Some declarations nest. A "goods to declare" annex is its own sub-packet clipped inside the main one - a nested FormGroup, a group living inside a group. And when the rule is "list every family member travelling with you," the desk hands over a form that grows a new row per person: that variable-length, add-and-remove list is a FormArray, whose length is not known until the traveler fills it in.

The desk tracks more than pass/fail. It notes whether the traveler has even reached a field yet (touched), and whether they have changed it from its printed default (dirty). This lets the desk be polite: it does not flag a box red before the traveler has had a chance to fill it. The whole packet is cleared for entry only when every inspector's stamp reads VALID - form.valid is the logical AND of all its controls, recomputed live as values change.

The failure mode is the clerk who tears up the packet and prints a fresh blank one every time the traveler so much as glances away from the counter. All entered data is lost, every inspector's stamp resets, and the traveler must start over on each interruption. In Angular this is exactly what happens when the FormGroup is constructed inside the template or rebuilt on each change-detection pass instead of once in the component: the model is re-created out from under the user, discarding half-entered values and validation state. The office record must be built once and persist for the life of the visit - not reissued on every render.


Syntax or Core Structure

A reactive form is a tree of FormControl, FormGroup, and FormArray objects built in the component class, then bound to the template with [formGroup] and formControlName. Validators are functions attached at construction; Angular runs them and aggregates the results into each control's valid, errors, and the group's overall validity.

@Component({
  selector: 'app-login',
  template: '<form [formGroup]="form"><input formControlName="email"></form>'
})
export class LoginComponent {
  form = new FormGroup({
    email: new FormControl('', [Validators.required, Validators.email]),
    password: new FormControl('', [Validators.required, Validators.minLength(6)])
  });
  submit() {
    if (this.form.valid) console.log(this.form.value);
  }
}

The model is pure data plus pure validator functions, so its validity is fully computable without a browser. This model builds a group of controls, runs each validator, and folds control validity into the group:

const V = {
  required: v => (v === '' || v == null) ? 'required' : null,
  minLength: n => v => (v && v.length < n) ? 'minlength' : null,
  email: v => (v && !v.includes('@')) ? 'email' : null
};
function control(value, validators = []) {
  const errors = {};
  for (const fn of validators) { const e = fn(value); if (e) errors[e] = true; }
  return { value, valid: Object.keys(errors).length === 0, errors };
}
function group(controls) {
  const value = {}; let valid = true;
  for (const [name, c] of Object.entries(controls)) {
    value[name] = c.value; if (!c.valid) valid = false;
  }
  return { value, valid };
}

const form = group({
  email: control('ada@x.com', [V.required, V.email]),
  password: control('123', [V.required, V.minLength(6)])
});
console.log('value: ' + JSON.stringify(form.value));
console.log('valid: ' + form.valid);

Output:

value: {"email":"ada@x.com","password":"123"}
valid: false

The email passes, but the six-character rule fails on "123", so the single invalid control drives the whole group invalid - which is exactly why the submit handler gates on form.valid.


Technical Depth: State, Structure, and Custom Validation

Control state flags

Every control carries status beyond its value. These flags are what let a form show errors at the right moment - typically only once a field is touched and invalid - rather than shouting red on a pristine form.

FlagMeaning
valid / invalidWhether all validators pass
pristine / dirtyWhether the value has been changed by the user
untouched / touchedWhether the control has been blurred
pendingAn async validator is still running
valueThe control's current value
errorsMap of failed validator keys, or null

A common template guard reads form.get('email')?.touched && form.get('email')?.invalid before rendering an error message, so the message appears only after the user has interacted with and left the field.

The FormBuilder shorthand

Writing new FormControl repeatedly is verbose. FormBuilder (injected as fb) offers a terser factory that produces the very same objects - a control becomes ['', Validators.required] and a group a plain object of those tuples:

form = this.fb.group({
  email: ['', [Validators.required, Validators.email]],
  password: ['', [Validators.required, Validators.minLength(8)]]
});

The result is identical to hand-built controls, so everything about validity and state behaves the same; FormBuilder is pure syntactic sugar that keeps larger forms readable. The NonNullableFormBuilder variant additionally makes each control non-nullable, so reset() returns to the initial value instead of null.

Nested groups and FormArray

When the number of fields is fixed but grouped, use a nested FormGroup; when the count varies at runtime, use a FormArray. An array's validity is the AND of its entries, and its length is dynamic - the user can push and remove controls. Modeled as a fold over its values:

function required(v) { return v === '' ? 'required' : null; }
function formArray(values) {
  const controls = values.map(v => ({ value: v, valid: required(v) === null }));
  return {
    value: controls.map(c => c.value),
    length: controls.length,
    valid: controls.every(c => c.valid)
  };
}
console.log(JSON.stringify(formArray(['ng', 'ts'])));
console.log(JSON.stringify(formArray(['ng', ''])));

Output:

{"value":["ng","ts"],"length":2,"valid":true}
{"value":["ng",""],"length":2,"valid":false}

Two filled entries validate; one empty entry fails its required check and pulls the whole array invalid, mirroring how a real FormArray aggregates its controls.

Custom and cross-field validators

A validator is just a function that returns null when valid or an errors object when not. A cross-field rule - "confirm must equal password" - cannot live on a single control, because it needs to see two values. It belongs on the enclosing FormGroup, whose validator receives the whole group:

function passwordsMatch(group) {
  return group.password === group.confirm ? null : { mismatch: true };
}
console.log(JSON.stringify(passwordsMatch({ password: 'a', confirm: 'a' })));
console.log(JSON.stringify(passwordsMatch({ password: 'a', confirm: 'b' })));

Output:

null
{"mismatch":true}

Matching values return null (valid); differing values return the { mismatch: true } errors object, which surfaces on group.errors. Because the validator is attached to the group, it re-runs whenever either member changes - the property the next section shows is easy to get wrong.


Real World Example: A Signup Form With Password Confirmation

Almost every signup form needs a "confirm password" field that must match the first. Here is a component that wires up email, password, and confirm - attaching the match check to the confirm control, which is the intuitive but flawed placement:

@Component({
  selector: 'app-signup',
  template: '<form [formGroup]="form"><button (click)="submit()">Join</button></form>'
})
export class SignupComponent {
  form = new FormGroup({
    email: new FormControl('', [Validators.required, Validators.email]),
    password: new FormControl('', [Validators.required, Validators.minLength(8)]),
    confirm: new FormControl('', [Validators.required, this.match.bind(this)])
  });

  // attached to the CONFIRM control - only re-runs when confirm changes
  match(control: AbstractControl): ValidationErrors | null {
    const password = this.form?.get('password')?.value;
    return control.value === password ? null : { mismatch: true };
  }

  submit() {
    if (this.form.valid) console.log(this.form.value);
  }
}

A control-level validator only re-runs when its own control's value changes. So if the user confirms a matching password and then edits the password field, the confirm validator never fires again and its last verdict stands. Compare that with a group-level validator, which re-runs on any member change:

function groupMatch(g) { return g.password === g.confirm ? 'ok' : 'mismatch'; }

// group-level: recomputed when password is edited
console.log('group after password edit: ' +
  groupMatch({ password: 'secret2', confirm: 'secret1' }));

// control-level on confirm: password edit does NOT re-run it; last result stands
const lastConfirmResult = groupMatch({ password: 'secret1', confirm: 'secret1' });
console.log('control after password edit (stale): ' + lastConfirmResult);

Output:

group after password edit: mismatch
control after password edit (stale): ok

The form's straightforward parts work well. Email and password each have clear, independent validators; the submit handler gates on form.valid so no incomplete data escapes; and binding through [formGroup] keeps the model authoritative. For the common flow - type a password, then type a matching confirmation - the mismatch check even appears to work, because the confirm validator runs as the user types into that field.

The trouble is the sequence the model above captures. Suppose the user types secret1 in both fields (valid), then goes back and changes the password to secret2. The group-level check, re-evaluated on that edit, correctly reports mismatch. The control-level check on confirm does not re-run at all, because confirm's own value never changed - so its stored verdict remains ok.

The result is a form that reports itself valid while displaying two different passwords, and it will happily submit. Worse, the bug is invisible in the most common test path and only appears when a user edits the first field after confirming - a real and frequent action when someone mistypes and corrects the original password.

The genuine design flaw is placing a cross-field validator on a single child control. A validator that depends on sibling values must live on the common ancestor - the FormGroup - via new FormGroup({...}, { validators: passwordsMatch }), so Angular re-evaluates it whenever any member changes. The confirm-control placement bakes in a stale-state bug; the group-level placement is the correct home for any rule that spans more than one field.


Common Mistakes

  1. Building the FormGroup in the template or on every change detection. Re-creating the model discards entered values and validation state. Construct it once as a class field or in ngOnInit.
  1. Putting a cross-field validator on a child control. It only re-runs when that control changes, so edits to a sibling leave a stale verdict. Attach rules that span fields to the FormGroup.
  1. Forgetting to import ReactiveFormsModule. Without it, [formGroup] and formControlName silently do nothing (or throw), and the form never binds.
  1. Calling a validator instead of passing it. Validators.required is passed by reference; writing Validators.required() or Validators.minLength without its argument breaks validation.
  1. Reading form.value for disabled controls. Disabled controls are omitted from value; use form.getRawValue() when you need every field including disabled ones.
  1. Showing errors on a pristine form. Displaying validation messages before the user touches a field is noisy. Gate messages on touched (or dirty) plus invalid.
  1. Mutating the form model directly. Assigning to control.value does not update state or trigger validation. Use setValue, patchValue, or reset.
  1. Using setValue with a partial object. setValue requires every control; a partial object throws. Use patchValue to update a subset.
  1. Treating async validators as synchronous. An async validator returns an Observable/Promise and the control is pending until it resolves. Checking valid immediately misreads a still-pending control.

Best Practices

  • Build the form model once in the component (a class field or ngOnInit) so its values and validation state persist across renders.
  • Place cross-field validators on the enclosing FormGroup, and single-field rules on the control, so each rule re-runs exactly when its inputs change.
  • Prefer FormBuilder (fb.group({...})) for concise construction of larger forms; it reads more clearly than repeated new FormControl calls.
  • Show validation messages only after a control is touched and invalid, keeping a fresh form quiet until the user has engaged with it.
  • Use patchValue for partial updates and setValue only when supplying every control, and reset to return a form to its initial state.
  • Type your forms - use FormControl<string> and typed groups (or NonNullableFormBuilder) so value has a precise, non-nullable shape.
  • Keep validators pure functions that depend only on the control value, making them trivial to unit-test in isolation.
  • Bind form state to the template with the control flags (invalid, errors, pending) rather than tracking submission or error status in separate component variables.

Practice Exercises

  1. Build a typed login form. Create a FormGroup with email (required + email) and password (required + minLength 8), bind it with [formGroup] and formControlName, and disable the submit button while form.invalid.
  1. Fix the cross-field validator. Start from a signup form whose match check sits on the confirm control, reproduce the stale-verdict bug by editing the password after confirming, then move the validator to the FormGroup and verify it re-runs.
  1. Use a FormArray. Build a form with a dynamic list of "skills," add buttons to push and remove entries, mark each entry required, and display the array's overall validity as the user edits.
  1. Gate error messages on state. Add inline error text for each field that appears only when the control is both touched and invalid, and confirm a freshly loaded form shows no errors until the user interacts with it.