In Angular Material, why does a mat-autocomplete of adjuster objects put [object Object] in the input, and what does displayWith change?
answer
- the option value lands in the input
- an object turned into a string
- a mapper from value to text
- string while typing, object after
- requireSelection resets to null
basics
~20 sPicking 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.
solid answer
~50 s`mat-autocomplete` attaches a panel of `<mat-option>`s to an input through the `matAutocomplete` directive. When the user picks an option, the trigger writes the option's value both to the form control and into the input; for an object that text is `[object Object]`. Bind `[displayWith]` to a function `(value) => string`, say `a => a?.name ?? ''`, and the input shows that text while the control keeps the whole adjuster object. The same function formats a value written from code, such as a loaded claim. Two things follow: while the user types, the control holds the typed string, so your filter and `displayWith` must accept both shapes; and with `requireSelection`, typing leaves the control alone and leaving without a pick resets it to `null`. Declare `displayWith` as an arrow function, because it is called without your component as `this`.
code
ts · 32 linesimport {Component, computed, signal} from '@angular/core';
import {FormControl, ReactiveFormsModule} from '@angular/forms';
import {MatAutocompleteModule} from '@angular/material/autocomplete';
import {MatInputModule} from '@angular/material/input';
interface Adjuster { id: string; name: string; }
@Component({
selector: 'app-adjuster-field',
imports: [ReactiveFormsModule, MatInputModule, MatAutocompleteModule],
template: `
<mat-form-field>
<mat-label>Assigned adjuster</mat-label>
<input matInput [formControl]="adjuster" [matAutocomplete]="auto"
(input)="query.set($any($event.target).value)" />
<mat-autocomplete #auto="matAutocomplete" requireSelection [displayWith]="adjusterName">
@for (a of matches(); track a.id) {
<mat-option [value]="a">{{ a.name }}</mat-option>
}
</mat-autocomplete>
</mat-form-field>
`,
})
export class AdjusterField {
readonly adjusters = signal<Adjuster[]>([]);
readonly adjuster = new FormControl<Adjuster | null>(null);
readonly query = signal('');
readonly matches = computed(() =>
this.adjusters().filter(a => a.name.toLowerCase().includes(this.query().toLowerCase())));
readonly adjusterName = (a: Adjuster | string | null) =>
typeof a === 'string' ? a : a?.name ?? '';
}go deeper
Remember that the input shows the option value unless displayWith maps it to text, and that you write the filtering yourself.
Explain what the control holds while typing, after a pick and after leaving, with and without requireSelection, and write a displayWith that accepts strings.
Choose requireSelection when the payload needs a real entity, move filtering off valueChanges accordingly, and guard submit code against the string case.
Decide whether shared lookup fields in a product commit only picked entities, and make that the default through MAT_AUTOCOMPLETE_DEFAULT_OPTIONS rather than per field.
## What `mat-autocomplete` does, and what it leaves to you Angular Material's autocomplete has two halves. `<mat-autocomplete #auto="matAutocomplete">` is the panel holding `<mat-option>` elements, and the **`matAutocomplete`** directive on an `<input>` (or `<textarea>`) is the trigger that opens the panel, handles the keyboard and talks to the form. The trigger is itself a `ControlValueAccessor`, so `[formControl]` or `formControlName` go on the same input, and the input still carries `matInput` so it lives inside `<mat-form-field>`. What it does **not** do is filter. The panel shows whichever options you render; narrowing them to what the user typed is your code, usually a `computed` or an observable over the typed text. ## Why the input shows `[object Object]` On an insurance claim intake form, an adjuster field searches the claims team. Each option carries the whole adjuster: `<mat-option [value]="adjuster">{{ adjuster.name }}</mat-option>`. When the user picks one, the trigger does two things: 1. It sends the option's value, the adjuster object, to the form control. 2. It writes a display value into the input. With no mapping, that display value is the option value itself, and assigning an object to an input's text turns it into `[object Object]`. ## `displayWith` `displayWith` is an input on `<mat-autocomplete>` that takes `(value: any) => string`. The trigger runs it to turn a control value into the input's text: ```ts readonly adjusterName = (a: Adjuster | string | null) => typeof a === 'string' ? a : a?.name ?? ''; ``` ```html <mat-autocomplete #auto="matAutocomplete" [displayWith]="adjusterName"> ``` The form control still holds the adjuster object; only the text changes. The same function runs when a value is written from code, for example `patchValue` with a saved claim's adjuster, so the edit screen shows a name too. ## What the control holds, and when | Moment | Default | With `requireSelection` | |---|---|---| | User types "Mar" | the string `"Mar"` | unchanged; typing is not written to the control | | User picks an option | the adjuster object | the adjuster object | | User edits the text and leaves without picking | the edited string | reset to `null` | | User opens and closes the panel without changing the text | unchanged | unchanged | Consequences worth saying out loud in an interview: - With the default behaviour, the control's type is really `Adjuster | string | null`. A validator that requires an object, or a submit handler that reads `adjuster.id`, must handle the string case. - `displayWith` can be called with a string, so write it to pass strings through, as above. - With **`requireSelection`**, the control only ever holds an adjuster or `null`, which is what a claim payload usually needs. Because typing no longer reaches the control, drive the filter from the input's own text (an `(input)` handler or a signal), not from the control's `valueChanges`. - `requireSelection`, `autoActiveFirstOption` and similar defaults can be set app-wide with `MAT_AUTOCOMPLETE_DEFAULT_OPTIONS`. ## Filtering for both shapes ```ts readonly query = signal(''); readonly matches = computed(() => { const q = this.query().toLowerCase(); return this.adjusters().filter(a => a.name.toLowerCase().includes(q)); }); ``` Feeding `query` from the input's text keeps the filter working in both modes. If you prefer `valueChanges`, map each value with `typeof v === 'string' ? v : v?.name ?? ''` first. ## Pitfalls - **`this` inside `displayWith`.** The panel calls the function as its own member, so a class method that reads `this.locale` sees the autocomplete, not your component. Use an arrow-function property. - **Reading `optionSelected` for the value.** The `optionSelected` output carries a `MatAutocompleteSelectedEvent` whose `option.value` is the object; it is useful for side effects, but the form control already has the value. - **Expecting built-in filtering.** Without your filter, every option shows no matter what is typed. - **Submitting a string.** In the default mode a user can type a name and never pick, leaving a string in the control. Either turn on `requireSelection`, or add a validator that rejects string values so the field reports an error. - **Formatting in two places.** Use the same function for the option text and `displayWith` when the two should read alike, so a renamed field changes both. ## In one line each - The option value goes to the control; `displayWith` decides what the input shows. - Typing writes strings unless `requireSelection` is on, in which case only picks or `null` reach the control. - Filtering is yours; drive it from the text the user typed.
- With requireSelection on, why does a filter built on the control's valueChanges stop updating?With `requireSelection`, the trigger deliberately does not write typed text to the form control; the control only changes when an option is picked or when it is reset to `null` on leaving. `valueChanges` therefore stays silent while the user types. Drive the filter from the input's own text, for example an `(input)` handler feeding a signal.
- Does displayWith run when the form is patched from code?Yes. The trigger's `writeValue` passes the incoming value through `displayWith` before writing the input's text, so patching a saved claim's adjuster object shows the adjuster's name. Without `displayWith`, the edit screen would show `[object Object]` before the user touches anything.
- mat-autocomplete filters its options as the user types.
- displayWith changes the value stored in the form control.
- After a selection the control holds the displayed name string.
- A displayWith class method can read component fields through this.
- requireSelection stops the user from typing text that matches no option.