首页 文章

如果它是一个对象,则值在mat-select下拉列表中不绑定

提问于
浏览
0

我正在使用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>

Component

在组件中,我从数据库中获取了此值 .

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

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

所以在这里我期待下拉应该选择值 Subject 1 . 但事实并非如此 .

1 回答

  • 1

    嗨@Surjeet Bhadauriya

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

    我在Stackblitz上创建了一个演示

    mat-select 中使用 [compareWith]="compareObjects" 作为使用对象

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

相关问题