簡體   English   中英

如果值是對象,則在mat-select下拉列表中未綁定值

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

我正在使用角度材質。

問題在於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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM