gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:21:55 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com