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

标签 javascript angular angular-material mean-stack

我正在使用 Angular Material。

问题出在 mat-select 上。它不绑定(bind)记录编辑的值。

这是我的代码..

HTML

如您所见,我在模型中绑定(bind)了 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;
}

关于javascript - 如果值是一个对象,则该值在 mat-select 下拉列表中不具有约束力,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51121536/

相关文章:

javascript - 如何将 DataTable 与对象数组一起使用?

javascript - 未实现页面之间的 Angular 7 数据更新

javascript - 将 JS 数组拆分为 N 个数组

javascript - 如何确保 Javascript 中的类属性类型正确?

html - Angular 2 日期输入未绑定(bind)到日期值

angularjs - Angular Material sidenav 事件广播

angular-material - 角 Material : How to display one toast after another one is displayed while keeping both on screen?

javascript - 缩放 mesh1,mesh2 自动改变它的位置?

javascript - 在 React useEffect Hook 中引用过时的状态

angularjs - 如何在 Angular Material 中获取事件选项卡