0

I spent a lot of time solving this problem and failed. I want to select to display the name and get the id. The problem is, as soon as a value is selected, the number (id) of that value is displayed. My code:

          <mat-form-field class="example-full-width">
            <input
            matInput
            placeholder="Search your product"
            formControlName="id"
            [matAutocomplete] = "auto">
            <mat-autocomplete #auto="matAutocomplete" > 
                  <mat-option    *ngFor="let option of allProducts; let i = index"   [value]="option.id"   >
                {{ option.name }}
              </mat-option>
            </mat-autocomplete>
          </mat-form-field>

I tried to create a function (onSelectionChange) but could not display the name and take the value as (id)

1 Answers1

1

Well, you have to use the input function of auto-complete called displayWith.

you can find the solution to your problem in this link here

plus I 've made a stackblitz example for you to simplify it more.

Example

to describe the solution:

you have to add to your autocomplete component an input called displayWith

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

and then in your component you have to create the function checkValue

checkValue(value: any) {
// here you can get your id or whatever you want
console.log(value)
}  

then you have to add to your mat option the value and give it your whole object as value

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

Please check the stackblitz example for more details

a bouchenafa
  • 272
  • 1
  • 9
  • 21
  • I am copy/paste solution from internet displayFn(item) { return this.matAutocomplete.options.filter(x => x.value === item).map(x => x.viewValue)[0] ? this.matAutocomplete.options.filter(x => x.value === item).map(x => x.viewValue)[0] : item; } patchFormData() { this.form.controls['id'].setValue(1); } – AleksandarMihailovic Dec 01 '19 at 13:44
  • check this https://stackblitz.com/edit/angular-otood2?file=src/app/autocomplete-simple-example.html – a bouchenafa Dec 01 '19 at 19:45
  • okey try to help me here https://stackoverflow.com/questions/59129383/how-to-configure-date-picker-angular-to-send-me-rfc-2822-format-angula-6-dat – AleksandarMihailovic Dec 01 '19 at 19:54