Angular AutoComplete is returning value as [Object Object]

Gvs Akhil picture Gvs Akhil · Mar 11, 2019 · Viewed 12.2k times · Source

My requirement was to show the selected value in the Input Box and get the Selected Id and Value to the .ts file. As I need the Id and Value I am binding the option value directly to [value]. But if I do that it's getting printed as [Object Object].

<mat-form-field appearance="outline" class="w-100">
            <mat-label>Enter Hotel Name</mat-label>
            <input type="text" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto">
            <mat-autocomplete #auto="matAutocomplete" (optionSelected)="selectedclient($event)">
                <mat-option *ngFor="let option of clients; let i = index" [value]="option">
                    {{ option.name }}
                  </mat-option>
            </mat-autocomplete>
            <mat-icon matSuffix>location_on</mat-icon>
          </mat-form-field>

Ts File

    options = [
        { id: 1, name: 'One'},
        { id: 2, name: 'Two'},
        { id: 3, name: 'Three'}
       ];

selectedclient(event) {
     console.log(event.option.value);
   }

Stackblitz Editor URL: https://stackblitz.com/edit/angular-mat-select-data-n4tvmj

Answer

Jeto picture Jeto · Mar 11, 2019

You want to make use of the displayWith attribute. Per the manual:

If you want the option's control value (what is saved in the form) to be different than the option's display value (what is displayed in the text field), you'll need to set the displayWith property on your autocomplete element. A common use case for this might be if you want to save your data as an object, but display just one of the option's string properties.

To make this work, create a function on your component class that maps the control value to the desired display value. Then bind it to the autocomplete's displayWith property.

Template side

<mat-autocomplete ... [displayWith]="getOptionText">

Script side

getOptionText(option) {
  return option.name;
}

Demo: https://stackblitz.com/edit/angular-mat-select-data-cddqia