如果值是对象,则值在 mat-select 下拉列表中不具有约束力

Value is not binding in mat-select drop-down if it is an object

我正在使用 Angular Material。

问题出在 mat-select。它不绑定记录编辑时的值。

这是我的代码..

HTML

如您所见,我在模型中绑定了 test.subject(一个对象),并在下拉列表中显示 subject.title 作为文本。

   <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>

组件

在组件中,我从数据库中获取了这个值。

this.test = {
   "subject": {
       "_id": "5b3883b4067d8d2744871eff",
       "title": "Subject 1"
    }
}

this.subjects = [
   {
       "_id": "5b3883b4067d8d2744871eff",
       "title": "Subject 1"
   },{
        "_id": "5b3843b4067d8d2744435erx",
        "title": "Subject 2"
   }
]

所以在这里我希望下拉列表应该选择值 Subject 1。但事实并非如此。

嗨@Surjeet Bhadauriya

您可以尝试使用此解决方案。

我已经在 Stackblitz

上创建了一个演示

使用 [compareWith]="compareObjects" 用于 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;
}