Reputation: 7156
I am using Angular Material.
The issue issue is with mat-select
. It is not binding the value on edit of record.
Here is my code..
HTML
Here as you can see I bound test.subject
(an object) in the model and showing subject.title
in the drop-down as a text.
<mat-form-field>
<mat-select [(ngModel)]="test.subject" placeholder="Subject" name="subject">
<mat-option>--</mat-option>
<mat-option *ngFor="let subject of subjects" [value]="subject">
{{subject.title}}
</mat-option>
</mat-select>
</mat-form-field>
Component
In the component, I got this value from the database.
this.test = {
"subject": {
"_id": "5b3883b4067d8d2744871eff",
"title": "Subject 1"
}
}
this.subjects = [
{
"_id": "5b3883b4067d8d2744871eff",
"title": "Subject 1"
},{
"_id": "5b3843b4067d8d2744435erx",
"title": "Subject 2"
}
]
So here I am expecting the drop down should be selected with value Subject 1
. But it is not.
Upvotes: 2
Views: 7263
Reputation: 9687
Hi @Surjeet Bhadauriya
You can try with this solution.
I have create a demo on Stackblitz
use [compareWith]="compareObjects"
for use object in mat-select
component.html
<mat-form-field>
<mat-select [compareWith]="compareObjects" [(ngModel)]="test.subject" placeholder="Subject" name="subject">
<mat-option>--</mat-option>
<mat-option *ngFor="let subject of subjects" [value]="subject">
{{subject.title}}
</mat-option>
</mat-select>
</mat-form-field>
component.ts
test: any;
subjects: Array<any>;
compareObjects(o1: any, o2: any): boolean {
return o1.name === o2.name && o1._id === o2._id;
}
Upvotes: 10