← Back to Angular, page 2

angular-0025 · Medium mid

How do typed reactive forms work, including FormArray, nonNullable controls, and a custom cross-field validator?

Typed forms infer types from how you create controls, so form.value and control.value are checked by TypeScript. Use nonNullable controls to avoid null, FormArray for repeating rows, and getRawValue() to include disabled controls. A cross-field rule is a validator attached to the group, not a control.

Full answer

Since Angular 14, FormControl, FormGroup, and FormArray carry types. If you write new FormControl(''), its type is FormControl<string | null>, because reset() sets it back to null. Two ways to avoid null:

  • new FormControl('', { nonNullable: true }), or
  • inject(NonNullableFormBuilder) (or fb.nonNullable), where all controls are non-null by default and reset() returns to the initial value.

form.value has type Partial<...>, since disabled controls are left out of it. To get every control, including disabled ones, with full types, call form.getRawValue().

FormArray<FormGroup<...>> handles repeating rows, such as the questions in a quiz. Add rows with push, remove with removeAt, and render with @for (row of form.controls.questions.controls; track row).

Validators are functions of type ValidatorFn: they receive the control and return null when valid, or an object of errors. A rule across two fields (pass mark must not exceed total marks) belongs on the parent group, since only the group can see both controls. Show its error with form.errors?.['passTooHigh'].

Other typed tools: FormRecord for a dynamic set of controls with the same type, and UntypedFormGroup as an escape hatch while migrating old code. Async validators return an Observable or Promise and run only after sync validators pass.

Remember to mark controls and groups as touched before showing errors, so users see them on submit.

typescript
import { Component, inject } from '@angular/core';
import {
  AbstractControl,
  NonNullableFormBuilder,
  ReactiveFormsModule,
  ValidationErrors,
  ValidatorFn,
  Validators,
} from '@angular/forms';

export const passNotAboveTotal: ValidatorFn = (group: AbstractControl): ValidationErrors | null => {
  const total = group.get('total')?.value as number | null;
  const pass = group.get('pass')?.value as number | null;
  return total !== null && pass !== null && pass > total ? { passTooHigh: true } : null;
};

@Component({
  selector: 'app-quiz-builder',
  imports: [ReactiveFormsModule],
  template: `
    <form [formGroup]="form" (ngSubmit)="save()">
      <input formControlName="title" placeholder="Quiz title" />
      <input type="number" formControlName="total" aria-label="Total marks" />
      <input type="number" formControlName="pass" aria-label="Pass marks" />
      @if (form.errors?.['passTooHigh']) {
        <small role="alert">Pass marks cannot be more than total marks.</small>
      }

      <div formArrayName="questions">
        @for (q of form.controls.questions.controls; track q; let i = $index) {
          <div [formGroupName]="i">
            <input formControlName="text" placeholder="Question {{ i + 1 }}" />
            <button type="button" (click)="removeQuestion(i)">Remove</button>
          </div>
        }
      </div>

      <button type="button" (click)="addQuestion()">Add question</button>
      <button type="submit" [disabled]="form.invalid">Save</button>
    </form>
  `,
})
export class QuizBuilderComponent {
  private readonly fb = inject(NonNullableFormBuilder);

  readonly form = this.fb.group(
    {
      title: ['', Validators.required],
      total: [100, [Validators.required, Validators.min(1)]],
      pass: [35, [Validators.required, Validators.min(0)]],
      questions: this.fb.array([this.newQuestion()]),
    },
    { validators: passNotAboveTotal },
  );

  private newQuestion() {
    return this.fb.group({ text: ['', Validators.required] });
  }

  addQuestion(): void {
    this.form.controls.questions.push(this.newQuestion());
  }

  removeQuestion(index: number): void {
    this.form.controls.questions.removeAt(index);
  }

  save(): void {
    const value = this.form.getRawValue();
    console.log(value.title, value.total, value.pass, value.questions.length);
  }
}

Angular 20.3, strict template type-checking passes. The same validator function can also be unit tested without rendering.

Key points

  • Types are inferred; use `nonNullable` to avoid `null` from `reset()`.
  • `value` is partial (disabled controls omitted); `getRawValue()` is complete.
  • A cross-field validator is attached to the group.
  • `FormArray` plus `push` and `removeAt` handle repeating rows.

Common mistakes

  • Putting a cross-field rule on one control, where it cannot see the other control reliably.
  • Reading `form.value.total` and forgetting it can be `undefined` in the type.
  • Using `UntypedFormGroup` out of habit and losing all type safety.

Follow-ups

  • How would you write an async validator that checks a username on the server?
  • What is the difference between `valueChanges` and `statusChanges`?
  • When would you choose `FormRecord`?

Tips

  • Explain why `reset()` makes values `null` by default. It shows you understand the types, not only the syntax.
  • Mention that disabled controls are excluded from `value`.
  • Keep validators as small pure functions and say they are easy to unit test.

Evaluation rubric

  • Understands inferred types and nonNullable.
  • Builds a FormArray and a group-level validator.
  • Knows value versus getRawValue.