Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MatAutocomplete value X display

My Autocomplete shows the values from an object with this definition:

export class Person {
  id: number;
  name: string;
  cityName: string;
}

This is the autocomplete template:

<mat-form-field class="example-full-width">
  <input type="text" placeholder="Person" aria-label="Person" matInput formControlName="personId" [matAutocomplete]="auto">

  <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn.bind(this)">
      <mat-option *ngFor="let item of filteredOptions" [value]="item">
        {{ item.name }}
      </mat-option>
  </mat-autocomplete>
</mat-form-field>

And this is the displayWith function:

displayFn(value?: any) {
  return value ? value.name : undefined;
}

It works, but the formControl binded to this autocomplete receives the entire item object:

 {
    id: 1;
    name: "John";
    cityName: "Dallas";
 }

How can I get only the "id" value in the formControl ?

like image 720
Beetlejuice Avatar asked Dec 13 '25 08:12

Beetlejuice


1 Answers

You have to do 2 things.

  1. Update the template so that the [value] bounds to id instead of the object.
  2. Update the displayFn so that the passed in id is used to lookup the object and return the name which will then be displayed in the input.
<mat-form-field class="example-full-width">
  <input type="text" placeholder="Person" aria-label="Person" matInput formControlName="personId" [matAutocomplete]="auto">

  <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn.bind(this)">
      <mat-option *ngFor="let item of filteredOptions" [value]="item.id">
        {{ item.name }}
      </mat-option>
  </mat-autocomplete>
</mat-form-field>
displayFn(value?: number) {
  return value ? this.filteredOptions.find(_ => _.id === value).name : undefined;
}
like image 181
Igor Avatar answered Dec 15 '25 23:12

Igor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!