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)
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.
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.