skip to content

Form Fields & Error States

mat-form-field wraps an input, select or autocomplete with a label, hint and error, shown once the control's ErrorStateMatcher says so. Interviewers ask how to fit your own control in.

part ofAngular Material & CDKread it →
on this pageshow

explore

questions

5

In Angular Material, how do you build a text field from mat-form-field, matInput, mat-label, mat-hint and mat-error, and what does each part do?

level: juniorimportance: must knowfreq 55%

answer

  1. a wrapper needs a control inside
  2. the directive on the native input
  3. label floats, hint sits underneath
  4. error takes the hint's place
  5. fill, fixed, and an app-wide token

basics

~20 s

mat-form-field wraps one control and draws its label, container and subscript line; matInput makes a native input that control. mat-label floats, mat-hint sits below, and mat-error takes the hint's place once the control is in an error state.

solid answer

~40 s

`<mat-form-field>` is a container: it draws the filled or outlined box, floats the `<mat-label>`, and owns a subscript line under the field. It renders no input itself; it needs one child that implements `MatFormFieldControl`, which is what the `matInput` directive gives a native `<input>` or `<textarea>`. Without one, a development build throws `mat-form-field must contain a MatFormFieldControl`. `<mat-hint>` holds helper text (`align="end"` for a counter), and `<mat-error>` messages use the same subscript slot, replacing the hints only while the control reports an error state. Every projected `<mat-error>` shows at once, so guard each with `@if (control.hasError('required'))`. The look comes from `appearance` (`fill` by default, or `outline`), `floatLabel` and `subscriptSizing`, set per field or app-wide through `MAT_FORM_FIELD_DEFAULT_OPTIONS`.

code

ts · 28 lines
ts
import {Component} from '@angular/core';
import {FormControl, ReactiveFormsModule, Validators} from '@angular/forms';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatInputModule} from '@angular/material/input';

@Component({
  selector: 'app-policy-number',
  imports: [ReactiveFormsModule, MatFormFieldModule, MatInputModule],
  template: `
    <mat-form-field>
      <mat-label>Policy number</mat-label>
      <input matInput [formControl]="policyNumber" maxlength="12" />
      <mat-hint>Printed on your insurance card</mat-hint>
      @if (policyNumber.hasError('required')) {
        <mat-error>Enter your policy number</mat-error>
      }
      @if (policyNumber.hasError('pattern')) {
        <mat-error>Use two letters followed by ten digits</mat-error>
      }
    </mat-form-field>
  `,
})
export class PolicyNumberField {
  readonly policyNumber = new FormControl('', {
    nonNullable: true,
    validators: [Validators.required, Validators.pattern(/^[A-Z]{2}\d{10}$/)],
  });
}

go deeper

for a junior

Recall the five pieces and what each draws: wrapper, matInput, label, hint, error. Know that the error replaces the hint and that each message needs its own @if guard.

for a middle

Explain that the wrapper only reads a MatFormFieldControl, that the matcher decides when errors show, and the trade between fixed and dynamic subscript sizing.

for a senior

Set the field look once through MAT_FORM_FIELD_DEFAULT_OPTIONS, and judge where dynamic subscripts are worth the layout shift in dense claim or checkout forms.

for a principal

Weigh a single app-wide field convention against per-team overrides, and decide which field behaviours a shared form library should lock down for every product.

## What `mat-form-field` is `<mat-form-field>` is Angular Material's wrapper for a **single form control**. It draws the Material 3 text-field container (filled or outlined), positions and floats the label, places prefixes and suffixes, and owns a **subscript** line under the field where helper text and error messages appear. It does not render an input of its own. It looks for one child that implements **`MatFormFieldControl`**, an abstract class describing the state the wrapper needs: an id, whether the control is focused, empty, required, disabled or in an error state, and a couple of methods. Material ships several implementations: the **`matInput`** directive (on `<input>` and `<textarea>`, and the same directive matches `select[matNativeControl]`), `<mat-select>`, `<mat-chip-grid>` and the date-range input. Your own component can be one too. In a standalone component, import `MatFormFieldModule` and `MatInputModule` (the input module re-exports the form-field module), or the individual classes such as `MatFormField`, `MatLabel`, `MatHint`, `MatError` and `MatInput`. ## The parts and what each does | Piece | Kind | Role | |---|---|---| | `<mat-form-field>` | component | Container, floating-label logic, subscript line | | `matInput` | directive on `<input>` / `<textarea>` | Makes the native element a `MatFormFieldControl` and tracks its error state | | `<mat-label>` | element | The label; floats above the value when the field is focused or filled | | `<mat-hint>` | element | Helper text; `align="end"` places it on the right, for example a character counter | | `<mat-error>` or `[matError]` | element | An error message, shown only while the control is in an error state | | `matTextPrefix`, `matIconSuffix` and friends | directives | Content before or after the value, such as a currency sign or an icon | ## A policy-number field On an insurance claim intake form, the policy number is a required field with a fixed format: ```html <mat-form-field appearance="outline"> <mat-label>Policy number</mat-label> <input matInput [formControl]="policyNumber" maxlength="12" /> <mat-hint>Printed on your insurance card</mat-hint> <mat-hint align="end">{{ policyNumber.value.length }} / 12</mat-hint> @if (policyNumber.hasError('required')) { <mat-error>Enter your policy number</mat-error> } @if (policyNumber.hasError('pattern')) { <mat-error>Use two letters followed by ten digits</mat-error> } </mat-form-field> ``` ## How the hint and the error share one line - The subscript shows **either** the hints **or** the errors, never both. When the control's `errorState` is true and at least one `<mat-error>` is projected, the errors replace the hints; otherwise the hints show. - **Every** `<mat-error>` you project renders while the field is in error. The wrapper does not know which validator a message belongs to, so guard each message with `@if (control.hasError('...'))`. - **When** `errorState` turns true is decided by the control's `ErrorStateMatcher`. The default rule is "invalid, and either touched or the parent form submitted", which is why an empty required field is not red on first render. - The subscript container is an `aria-live="polite"` region, so a newly shown message is announced by screen readers. ## Appearance, label and subscript inputs | Input | Values | Default | |---|---|---| | `appearance` | `'fill'`, `'outline'` | `'fill'` | | `floatLabel` | `'auto'`, `'always'` | `'auto'` | | `subscriptSizing` | `'fixed'`, `'dynamic'` | `'fixed'` | | `hideRequiredMarker` | boolean | `false` | `subscriptSizing="fixed"` reserves one line under every field and positions messages absolutely inside it, so the form never jumps, but a two-line error spills over whatever sits below. `"dynamic"` reserves nothing and lets the subscript grow with its content, at the price of layout shift when a message appears. `floatLabel="always"` keeps the label raised even when the field is empty and unfocused. Any of these can be set for the whole app through the **`MAT_FORM_FIELD_DEFAULT_OPTIONS`** injection token, for example `{provide: MAT_FORM_FIELD_DEFAULT_OPTIONS, useValue: {appearance: 'outline'}}` in the application's providers. An input on an individual field still wins over the token. ## Common mistakes 1. Leaving out `matInput`: a development build throws `mat-form-field must contain a MatFormFieldControl`. 2. Projecting several unguarded `<mat-error>` elements and seeing all of them at once. 3. Expecting the hint and the error to stack; the error replaces the hint for as long as it shows. 4. Using `placeholder` as the only label. Placeholder text is meant to show while the label floats over an empty input, and it disappears once the user types. 5. Fighting the layout with margins when a long error overlaps the next field, instead of choosing `subscriptSizing="dynamic"` for that field.

  • What happens if a mat-form-field contains a plain input without matInput?
    The wrapper finds no `MatFormFieldControl` child. In a development build it throws `mat-form-field must contain a MatFormFieldControl` during content initialisation, so the mistake surfaces at once rather than as a half-styled field. Adding `matInput` (and importing `MatInputModule` or `MatInput`) fixes it.
  • What does subscriptSizing="dynamic" change, and what does it cost?
    With the default `fixed`, every field reserves one line for hint or error text and the message is positioned absolutely, so a long error overlaps the next field. `dynamic` reserves no space and lets the subscript grow with its content, so nothing overlaps, but the layout shifts when a message appears or disappears.
  • How do you put a currency sign or an icon inside the field?
    Use the prefix and suffix directives on child elements: `matTextPrefix` or `matTextSuffix` for text such as a currency sign, `matIconPrefix` or `matIconSuffix` for a `<mat-icon>`. The form field places them inside the container next to the value and keeps the label aligned with them.

  • mat-form-field styles any input inside it, matInput is optional.
  • Each mat-error shows by itself only when its own validator fails.
  • The hint and the error both show under the field at the same time.
  • The default appearance of mat-form-field is outline.
  • An empty required field should turn red as soon as the page renders.
open as a page

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%

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.

open as a page

In Angular Material, why does a mat-autocomplete of adjuster objects put [object Object] in the input, and what does displayWith change?

level: middleimportance: should knowfreq 38%

basics

~20 s

Picking an option writes its value into the input, and an object becomes the text [object Object]. displayWith maps the control value to display text while the control keeps the object; while typing, the control holds the typed string.

open as a page

In Angular Material, why does a mat-select with object option values show blank for a loaded record, and what does compareWith fix?

level: middleimportance: should knowfreq 42%

basics

~20 s

mat-select matches its value to options with === by default, so a record loaded separately holds a different object than the option list and nothing is selected. compareWith supplies a function that compares a stable key such as an id.

open as a page

In Angular Material 22, how do you make a composite bank-account control, with routing and account number inputs, work inside mat-form-field as a MatFormFieldControl?

level: seniorimportance: should knowfreq 30%

basics

~10 s

Implement the MatFormFieldControl contract: provide MatFormFieldControl with useExisting, expose id, ngControl, focused, empty, shouldLabelFloat, required, disabled and errorState, and implement setDescribedByIds and onContainerClick. In v22 state may be signals, making stateChanges optional.

open as a page