pratik jaiswal
pratik jaiswal

Reputation: 2065

Angular material Autocomplete how to bind json object to mat-option

I have a very simple autocomplete example in which on every input change I search data in API's and return product_name and id. Now the problem is I need both name and id to be sent to the dialog later, but if I bind an object to mat-option [value] like [value]=option, the formcontrol shows [object][object].

But [value]=option.name works fine

How can I bind json object to mat-option [value] so that I can use both name and id

The data is of form {product_id: 4, name: "abc"}

.ts

getfiveProducts() {

    this.productService.get5Products().subscribe(data => {
      if(data){
        console.log(data)
        this.product_list = data

      }

    })
  }

  onSearchChange(value){

    debounceTime(200)

    this.productService.search_Products(value).subscribe(data =>{
      if(data){

        console.log(data)
        this.product_list = data
        console.log(value)
      }
    })

  }

.html

      <mat-form-field class="example-full-width">
        <mat-label>Enter product name</mat-label>

        <input matInput
               aria-label="product name"
               [matAutocomplete]="auto"
               formControlName ="product_name"
               (input)="onSearchChange($event.target.value)">


        <mat-autocomplete #auto="matAutocomplete">

          <mat-option *ngFor="let state of product_list " [value]="state.name">
            <span>{{state.name}}</span> 
          </mat-option>

          <mat-option *ngIf="!product_list || !product_list.length" class="text-danger">
            Such product does not exists
          </mat-option>

        </mat-autocomplete>

      </mat-form-field>

Upvotes: 0

Views: 2464

Answers (1)

pratik jaiswal
pratik jaiswal

Reputation: 2065

When you need to bind an object to mat-options [value], then you need to use displayWith property on your autocomplete element. This property will display the name for your field.

Enter product name

        <input matInput #input
               aria-label="product name"
               [matAutocomplete]="auto"
               formControlName ="product_name">


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

          <mat-option *ngFor="let state of product_list " [value]="state ">
            <span>{{state.name}}</span> 
          </mat-option>

          <mat-option *ngIf="!product_list || !product_list.length" class="text-danger">
            Such product does not exists
          </mat-option>

        </mat-autocomplete>

      </mat-form-field>

.ts

displayFn(product): string {
  return product? product.name: product;
}

link

Upvotes: 1

Related Questions