skip to content

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%

answer

  1. two objects that look the same
  2. the default comparison is strict
  3. no match clears the trigger
  4. compare by a stable key
  5. arrow function, null-safe

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.

solid answer

~40 s

When `<mat-option [value]="type">` carries objects, `mat-select` decides which option is selected by calling its comparator with each option's value and the bound value; the default is `(o1, o2) => o1 === o2`. A saved claim fetched from the API carries its own claim-type object, equal in content but not the same reference as the one in the options list, so no option matches and the trigger is cleared, while the form control still holds the object. Bind `[compareWith]` to a function that compares a stable key, for example `(a, b) => a?.code === b?.code`. Make it null-safe, because a reset passes `null`, and make it an arrow-function property, because the select calls it without your component as `this`. Binding primitive ids as option values avoids the problem altogether.

code

ts · 26 lines
ts
import {Component, signal} from '@angular/core';
import {FormControl, ReactiveFormsModule} from '@angular/forms';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatSelectModule} from '@angular/material/select';

interface ClaimType { code: string; label: string; }

@Component({
  selector: 'app-claim-type',
  imports: [ReactiveFormsModule, MatFormFieldModule, MatSelectModule],
  template: `
    <mat-form-field>
      <mat-label>Claim type</mat-label>
      <mat-select [formControl]="claimType" [compareWith]="sameType">
        @for (type of claimTypes(); track type.code) {
          <mat-option [value]="type">{{ type.label }}</mat-option>
        }
      </mat-select>
    </mat-form-field>
  `,
})
export class ClaimTypeField {
  readonly claimTypes = signal<ClaimType[]>([]);
  readonly claimType = new FormControl<ClaimType | null>(null);
  readonly sameType = (a: ClaimType | null, b: ClaimType | null) => a?.code === b?.code;
}

go deeper

for a junior

Remember that mat-select matches options with === unless you give it compareWith, so objects loaded separately look different even when equal.

for a middle

Explain the matching walk, why the trigger clears while the control keeps its value, and how to write a null-safe arrow comparator.

for a senior

Recognise the blank-on-edit symptom fast, and decide between compareWith, primitive option values or reusing option instances for a given form's payload.

for a principal

Set a team convention for object-valued selects so edit screens behave like create screens, and decide whether shared field components should demand a key accessor.

## How `mat-select` matches its value to an option `<mat-select>` is Angular Material's dropdown control. It implements `MatFormFieldControl`, so it sits inside `<mat-form-field>` like `matInput`, and it works with reactive forms, template-driven forms, Signal Forms or a plain `[(value)]` binding. Each `<mat-option>` has a `value`, which can be any type: a string, a number or an object. Whenever the bound value changes, the select walks its options and asks a **comparator** whether `option.value` matches the value. The first match is selected and its text appears in the trigger. If nothing matches, the select **clears the trigger**: it shows the empty field or the placeholder. The comparator is the `compareWith` input, and its default is strict identity: ```ts (o1: any, o2: any) => o1 === o2 ``` ## Why a loaded claim shows blank On an insurance claim intake form, the claim-type select lists objects fetched from a reference endpoint: `{code: 'WATER', label: 'Water damage'}`, `{code: 'THEFT', label: 'Theft'}` and so on. Creating a claim works, because the user picks an option and the control receives that very object. Editing a saved claim does not. The claim arrives from another request, and its `claimType` is a **new object** with the same fields. `patchValue` puts it in the control, the select compares it with each option using `===`, every comparison is false, and the trigger stays empty. Nothing is wrong with the form value; the control still holds the object, and submitting would send it. Only the display lost the link, which is exactly why this bug survives until someone opens an edit screen. Load order is rarely the culprit. If the claim types arrive after the claim, the select re-runs its matching whenever the option list changes, so a late list is fine as long as some option compares equal to the value. What never works is two different references compared with `===`. ## The fix: `compareWith` ```ts readonly sameType = (a: ClaimType | null, b: ClaimType | null) => a?.code === b?.code; ``` ```html <mat-select formControlName="claimType" [compareWith]="sameType"> @for (type of claimTypes(); track type.code) { <mat-option [value]="type">{{ type.label }}</mat-option> } </mat-select> ``` The select now calls `sameType(option.value, value)` and finds the option whose code matches the saved claim. ## Writing a comparator that does not bite - **Null-safe.** After `reset()` or before data arrives, the bound value is `null`, and the select still calls the comparator for each non-null option value. `(a, b) => a.code === b.code` then throws reading `code` of `null`. The select catches the exception, logs it with `console.warn` in development builds and treats the option as unmatched, so the symptom is a console full of warnings rather than a crash. Use optional chaining or an explicit null check. - **No `this`.** The select stores the function and calls it as its own member, so inside a class *method* `this` is the select, not your component. Declare the comparator as an arrow-function property, or keep it free of `this`. - **A function, not a string.** In a development build, assigning anything other than a function throws `` `compareWith` must be a function. `` - **Multiple selection.** With `multiple`, the value is an array and the comparator runs for each element against the options, so the same function works unchanged. - **Stable keys only.** Compare an id or code, never a label that can be renamed or translated. ## Alternatives | Approach | How | Trade-off | |---|---|---| | `compareWith` | Keep objects as values, compare by key | Form value stays rich; the comparator must be null-safe | | Primitive values | `[value]="type.code"` | No comparator needed; you look up the object when you need its label | | Reuse the option instance | Replace the loaded object with the matching one from the list before patching | Works with `===`, but every load path must remember to do it | Primitive values are often the simplest choice for a select whose submitted payload only needs the code. `compareWith` earns its place when the rest of the form genuinely works with the whole object. ## Common mistakes 1. Blaming change detection or load order when the trigger is blank, instead of checking identity. 2. Writing the comparator as a method that reads component fields through `this`. 3. Forgetting the `null` case and ignoring the development-mode warnings it produces. 4. Comparing by display label, which breaks after translation.

  • What does the select show, and what does the form hold, when no option matches the value?
    The select clears its trigger, so the field looks empty or shows its placeholder, and no option is marked selected. The form control is untouched and still holds the unmatched value, so the form value and the screen disagree until a comparator, or a matching option, restores the link.
  • Does compareWith work the same with multiple selection?
    Yes. With `multiple`, the bound value must be an array, and the select runs the comparator for each element against the options, selecting every match. The same key-based, null-safe function serves both modes.

A coat check matches coats by ticket number, not by asking whether you hold the exact paper slip it printed. A replacement slip with the same number still gets your coat; compareWith teaches mat-select to read the number.

  • mat-select compares option values with a deep equality check by default.
  • A blank select means the form control lost its value.
  • A comparator method can safely read component fields through this.
  • compareWith only matters when the select allows multiple selection.
  • Comparing by the option's label is as good as comparing by id.