One issue I am encountering is with a form that contains select boxes using objects as values:
<mat-option [value]="object">
While this works fine when creating new records, editing existing ones proves to be problematic because the object
in the mat-select-option
does not match exactly with the object retrieved from the rest service. Consequently, the select boxes do not display the correct option selected during record editing.
Is there a way to instruct the select-box widget to compare based on object.id
in order to determine the selected option? It seems like writing a directive might be necessary, or perhaps Angular or Angular Material libraries offer a solution already.
For further context, here is a snippet from my foo.component.ts
file:
let item = {
'fruit': { id: 1, 'label': 'Pineapple' },
}
let options = [
{ 'id':1, 'label': 'Pineapple' },
{ 'id':2, 'label': 'Banana' },
{ 'id':3, 'label': 'Papaya' }
]
In the corresponding .html
file:
<mat-select placeholder="Fruit" [(ngModel)]="item.fruit">
<mat-option *ngFor="let option of options" [value]="option">{{option.label}}</mat-option>
</mat-select>
When the page loads, the expected behavior would be for "Pineapple" to be pre-selected in the mat-select
. Since the 'pineapple' in the item.fruit
and the options
array are referencing different objects, the mat-select
remains empty.
An ideal implementation would look something like this:
<mat-select
placeholder="Fruit"
[(ngModel)]="item.fruit"
equalityAttr="id"
>