I have a mat-select where the options are all objects defined in an array. I am trying to set the value to default to one of the options, however it is being left selected
Use compareWith
, A function to compare the option values with the selected values. see here: https://material.angular.io/components/select/api#MatSelect
For an object of the following structure:
listOfObjs = [{ name: 'john', id: '1'}, { name: 'jimmy', id: '2'},...]
Define markup like this:
<mat-form-field>
<mat-select
[compareWith]="compareObjects"
[(ngModel)]="obj">
<mat-option *ngFor="let obj of listOfObjs" [value]="obj">
{{ obj.name }}
</mat-option>
</mat-select>
</mat-form-field>
And define comparison function like this:
compareObjects(o1: any, o2: any): boolean {
return o1.name === o2.name && o1.id === o2.id;
}
I followed the above very carefully and still couldn't get the initial value selected.
The reason was that although my bound value was defined as a string in typescript, my backend API was returning a number.
Javascript loose typing simply changed the type at runtime (without error), which prevented selection the of the initial value.
Component
myBoundValue: string;
Template
<mat-select [(ngModel)]="myBoundValue">
Solution was to update the API to return a string value.
Try this!
this.selectedObjectList = [{id:1}, {id:2}, {id:3}]
this.allObjectList = [{id:1}, {id:2}, {id:3}, {id:4}, {id:5}]
let newList = this.allObjectList.filter(e => this.selectedObjectList.find(a => e.id == a.id))
this.selectedObjectList = newList
You should be binding it as [value]
in the mat-option
as below,
<mat-select placeholder="Panel color" [(value)]="selected2">
<mat-option *ngFor="let option of options2" [value]="option.id">
{{ option.name }}
</mat-option>
</mat-select>
LIVE DEMO
I did it just like in these examples. Tried to set the value of the mat-select to the value of one of the mat-options. But failed.
My mistake was to do [(value)]="someNumberVariable" to a numeric type variable while the ones in mat-options were strings. Even if they looked the same in the template it would not select that option.
Once I parsed the someNumberVariable to a string everything was totally fine.
So it seems you need to have the mat-select and the mat-option values not only be the same number (if you are presenting numbers) but also let them be of type string.
Binding or setting of default value works only if the value attribute on MatSelect is comparable to value attribute binded to MatOption. If you bind caption
of your item to value attribute of mat-option element you must set the default element on mat-select to caption
of your item too. If you bind Id
of your item to mat-option, you must bind id
to mat-select too, not a whole item, caption or any other, only the same field.
But you need to do it with binding []