Reputation: 19298
I have a list of object I want to use in a AutoComplete. When a option gets selected the formConttrol gets the value of the selected item. Now I don't care about the entire object, I only care about the ID.I changed the option to have the id as value, but then the textinput remains empty.
<mat-option *ngFor="let option of filteredOptions | async" [value]="option.id">
{{option.name}}
</mat-option>
Example: https://stackblitz.com/edit/angular-b97y6e-jwm2jq?file=src%2Fapp%2Fautocomplete-display-example.ts
Is there any way to use a object attribute as value?
Upvotes: 1
Views: 813
Reputation: 920
The problem is you bind wrong value here-> [value]="option.id"
Solutation
<mat-option *ngFor="let option of filteredOptions | async" [value]="option">
{{option.name}}
</mat-option>
in your filteredOptions
there is not any id
paramater that's why its not working
So,
Change [value]="option.id"
to [value]="option"
it will be work fine ! check updated code
https://stackblitz.com/edit/angular-b97y6e-hsmvqn?file=src%2Fapp%2Fautocomplete-display-example.html
Upvotes: 0
Reputation: 56
The problem here is that [value] is always string. Use [ngValue] instead. Here you can pass objects and numbers (which are objects in javascript) etc.
Differences between value and ngValue in Angular 5
<mat-option *ngFor="let option of filteredOptions | async" [ngvalue]="option.id">
{{option.name}}
</mat-option>
Upvotes: 1