skip to content

In Angular Material, when does a mat-error inside mat-form-field become visible, and how do you change that rule with an ErrorStateMatcher?

level: middleimportance: must knowfreq 52%

answer

  1. the control decides, not mat-error
  2. invalid is not enough
  3. touched or the form submitted
  4. per input, subtree or app-wide
  5. group errors need a custom rule

basics

~20 s

A mat-error shows when the control's ErrorStateMatcher says so: by default, invalid and either touched or the parent form submitted. Pass a custom matcher to one control with [errorStateMatcher], or provide ErrorStateMatcher for a subtree or the app.

solid answer

~40 s

`<mat-error>` has no logic of its own: the form field shows errors whenever its control's `errorState` is true. `matInput` and `mat-select` compute that through an `ErrorStateMatcher`, whose default `isErrorState(control, form)` returns `control.invalid && (control.touched || form.submitted)`, where `form` is the parent `FormGroupDirective` or `NgForm`. So an empty required field stays quiet until it is blurred or the form is submitted. To change the rule, implement `isErrorState` and pass an instance through the `[errorStateMatcher]` input, or provide `ErrorStateMatcher` in a component's or the app's providers; Material also ships `ShowOnDirtyErrorStateMatcher`. A common reason is a group-level validator: the control itself is valid, so a matcher must also check `control.parent?.hasError(...)`. Keep it cheap, because it runs on every change-detection pass.

code

ts · 31 lines
ts
import {Component, inject} from '@angular/core';
import {FormBuilder, ReactiveFormsModule, Validators} from '@angular/forms';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatInputModule} from '@angular/material/input';
import {ClaimAmountMatcher, withinCoverage} from './claim-rules';

@Component({
  selector: 'app-claim-amount',
  imports: [ReactiveFormsModule, MatFormFieldModule, MatInputModule],
  template: `
    <form [formGroup]="claim" (ngSubmit)="file()">
      <mat-form-field>
        <mat-label>Claimed amount</mat-label>
        <input matInput type="number" formControlName="amount"
               [errorStateMatcher]="amountMatcher" />
        @if (claim.hasError('exceedsCoverage')) {
          <mat-error>Exceeds the coverage limit of this policy</mat-error>
        }
      </mat-form-field>
      <button type="submit">File claim</button>
    </form>
  `,
})
export class ClaimAmount {
  readonly claim = inject(FormBuilder).group(
    {amount: [0, Validators.required], coverageLimit: [5000]},
    {validators: withinCoverage},
  );
  readonly amountMatcher = new ClaimAmountMatcher();
  file() {}
}

go deeper

for a junior

Remember the default rule: invalid, and either touched or the form submitted. That is why an empty required field is not red until you leave it or press submit.

for a middle

Explain the matcher as the bridge between control state and the subscript, the three scopes for a custom one, and why group-level errors need one.

for a senior

Diagnose fields that never turn red or turn red after reset by checking submit wiring, resetForm versus reset, and matcher scope, and keep matchers cheap because they run every cycle.

for a principal

Decide one error-timing convention across products, blur, dirty or submit, and make it the provided default so individual teams do not each write their own matcher.

## Who decides that an error shows `<mat-error>` is only content. The surrounding `<mat-form-field>` switches its subscript from hints to errors when its control's **`errorState`** is true and at least one `<mat-error>` is projected. For `matInput` and `<mat-select>`, `errorState` comes from an **`ErrorStateMatcher`**, a small class from `@angular/material/core` with one required method: ```ts isErrorState(control: AbstractControl | null, form: FormGroupDirective | NgForm | null): boolean { return !!(control && control.invalid && (control.touched || (form && form.submitted))); } ``` That is the default implementation. `form` is the parent form directive: the `FormGroupDirective` behind `[formGroup]`, or the `NgForm` of a template-driven `<form>`. | What has happened | `touched` | `submitted` | Error shown for an invalid control | |---|---|---|---| | Page rendered | false | false | no | | User typed but has not left the field | false | false | no | | User left the field (blur) | true | false | yes | | User pressed the form's submit button | any | true | yes | The matcher only decides **when**. **Whether** the control is invalid is the validators' job, and which message to print is yours, usually one `@if (control.hasError('...'))` per `<mat-error>`. ## Where a matcher plugs in `matInput` and `mat-select` inject `ErrorStateMatcher` as their default (it is provided in the root injector out of the box) and accept an **`errorStateMatcher`** input that overrides it. Because a form submission cannot be subscribed to, `matInput` re-runs the matcher in `ngDoCheck`, on every change-detection pass; whatever you write there must be cheap. Three scopes are available: 1. **One control:** `<input matInput [errorStateMatcher]="amountMatcher">`. 2. **A subtree:** `providers: [{provide: ErrorStateMatcher, useClass: MyMatcher}]` on a component, so every Material control below it uses that rule. 3. **The whole app:** the same provider in `bootstrapApplication`. For the most common variant Material ships **`ShowOnDirtyErrorStateMatcher`**, which uses `dirty` instead of `touched`: errors appear on the first edit rather than on blur. ## A group error on a claim form On an insurance claim intake form, a validator on the `FormGroup` compares the claimed amount with the coverage limit of the chosen policy and sets `exceedsCoverage` **on the group**. The amount control's own validators pass, so `control.invalid` is false and the default matcher never shows the amount field's `<mat-error>`, even though the form cannot be submitted. A custom matcher fixes it by also looking at the parent: ```ts export class ClaimAmountMatcher implements ErrorStateMatcher { isErrorState(control: AbstractControl | null, form: FormGroupDirective | NgForm | null): boolean { const interacted = !!(control?.touched || form?.submitted); const invalid = !!(control?.invalid || control?.parent?.hasError('exceedsCoverage')); return invalid && interacted; } } ``` The field then turns red, and its guarded `<mat-error>` (checking `claim.hasError('exceedsCoverage')`) prints the message. ## Pitfalls around `submitted` - `submitted` is set by the browser's **submit event** on the `<form>` that carries `[formGroup]` or `ngForm`. A save button with `type="button"` and a click handler, or a button outside the form, never sets it, so untouched invalid fields stay quiet. - `FormGroup.reset()` resets the controls to pristine and untouched but **not** the directive's `submitted` flag. After a submitted form is reset, every empty required field turns red. Call `resetForm()` on the `FormGroupDirective` (or `NgForm`) instead; it resets the controls and sets `submitted` back to false. - A matcher that returns `control.invalid` alone shows errors on first render, before the user has typed anything. ## Debugging a field that never turns red 1. Check **where the error lives**: `control.errors` empty while the group has errors means the default matcher cannot see it. 2. Check **touched**: a custom control that never calls its touched callback never becomes touched, so only a submit can show its error. 3. Check **submit wiring**: is the button `type="submit"` and inside the `<form>` that carries the form directive? 4. Check **which matcher is injected**: a provider on a parent component silently replaces the root default for everything below it. ## Signal Forms A matcher may also implement the optional `isSignalErrorState(field)`, which `matInput` uses when it is bound to a Signal Forms field; the default version returns invalid and touched. `isErrorState` remains required on the class, and the input guide notes it can simply return false in a matcher meant only for signal forms. ## Summary - The control's matcher decides when; validators decide whether; your `@if` decides which text. - Default: invalid and (touched or submitted). `ShowOnDirtyErrorStateMatcher`: invalid and (dirty or submitted). - Reach for a custom matcher for group-level errors or a different timing, scoped as narrowly as the need.

  • Why must isErrorState stay cheap?
    `matInput` cannot subscribe to a parent form's submission, so it re-evaluates its error state in `ngDoCheck`, which runs on every change-detection pass for every field. A matcher that walks large structures, formats strings or calls services multiplies that cost across the whole form. Read flags on the control, its parent and the form, and nothing more.
  • A submitted form is reset with FormGroup.reset() and every empty required field turns red. Why, and what is the fix?
    `reset()` marks the controls pristine and untouched but leaves the `FormGroupDirective`'s `submitted` flag true, and the default matcher shows errors for invalid controls when the form is submitted. Call `resetForm()` on the directive (inject it or take it from a template reference) so `submitted` goes back to false.
  • How do you use a different rule for one form without changing the rest of the app?
    Provide `ErrorStateMatcher` in that form component's `providers`, for example with `useClass: ShowOnDirtyErrorStateMatcher`. `matInput` and `mat-select` inject the matcher from their element injector, so every Material control inside that component picks it up, while the rest of the app keeps the root default.

  • mat-error appears as soon as its validator fails.
  • The default matcher shows errors once the control is dirty.
  • FormGroup.reset() also clears the form's submitted flag.
  • A custom ErrorStateMatcher changes which validators run on the control.
  • Errors set on a FormGroup light up its fields automatically.