Home > Mobile >  Store Object with Angular Autocomplete, not only Value in Input
Store Object with Angular Autocomplete, not only Value in Input

Time:02-20

Working on Angular, I created an Input with mat-autocomplete and mat-option (data comes from an Object Array, using NgFor). Properties of Object are ID, name and email.

The autocomplete works, the filter works. The user can select successfully a filtered item from the list, and it gets reflected in the Input value.

The list of items correspond to a list of ID of each Object of the Array.

<mat-form-field appearance="outline">
            <mat-label>Id</mat-label>
            <input matInput
                
                type="text"
                placeholder="Id"
                aria-label="Number"
                formControlName = "ID"
                [matAutocomplete]="auto">
    
            <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
                <mat-option *ngFor="let customer of filteredCustomers | async" [value]="customer.ID">
                    {{ customer.ID }}
                  </mat-option>
            </mat-autocomplete>
            </mat-form-field>

The problem is: I can storage the Input Value (ID of Object selected), but I need to store the WHOLE Object, with all its properties. Not only ID, but Name and Email.

I looked up and from previous questions, a solution seems to be to assign the whole Object to [value]. Instead of:

[value]="customer.ID"

Do:

[value]="customer"

But then, my Input Value shows "Object Object" when selected. I need the user to be able to read the selected ID, and for the whole Object to get storaged.

How can I do that?

CodePudding user response:

Try using displayWith

<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">

displayFn(customer) { return customer.ID; }

CodePudding user response:

What you need is to set the displayWith property on your autocomplete element. It takes a Function that maps the option's value to it's display value.

You can do something as below:

<mat-autocomplete autoActiveFirstOption #auto="matAutocomplete" [displayWith]="displayFn">
  <mat-option *ngFor="let customer of filteredCustomers | async" [value]="customer">
    {{ customer.ID }}
  </mat-option>
</mat-autocomplete>

Define function in ts file as:

// Instead of 'any' type, use the type as per your use case
displayFn(customer: any): string {
  return customer && customer.ID ? customer.ID : '';
}

You can read more about it in the official docs along with the example: Setting separate control and display values

  • Related