html - 如何在不匹配属性名称的情况下在选择中使用对象子作为值
问题描述
我想将选择字段的值设置为repairData
名为 的属性中指定的值reportShiftId
,但它不起作用。另一方面,如果我在里面制作 Shift 对象repairData
并用它引用它就reportShift.id
可以了。
当我更改选择的 ng 模型时,在不工作的代码repairData.reportShiftId
中,选择选项不会改变,但是在我在选择中手动选择某些内容后,ngModel 开始正常工作。
不工作的代码:
export class RepairData {
reportShiftId: number;
...
}
-
<select class="form-control" name="shift" [(ngModel)]="repairData.reportShiftId">
<option *ngFor="let shift of shifts" [ngValue]="shift.id">{{shift.name}}</option>
</select>
工作代码:
export class RepairData {
reportShift: Shift;
...
}
-
<select class="form-control" name="shift" [(ngModel)]="repairData.reportShift.id">
<option *ngFor="let shift of shifts" [ngValue]="shift.id">{{shift.name}}</option>
</select>
如何使用reportShiftId
(数字)而不是reportShift.id
(Shift.number)?
解决方案
尝试像这样实现 compareWith 函数:
<select class="form-control" name="shift" [compareWith]="compareWithFunction" [(ngModel)]="repairData.reportShiftId">
<option *ngFor="let shift of shifts" [ngValue]="shift.id">{{shift.name}}</option>
</select>
compareWithFunction(item1,item2){
return item1 && item2 ? item1.id === item2.id : item1 === item2;
}
推荐阅读
- swift - SwiftUI - 带有切换 Bool 变量的按钮的数组列表
- javascript - 在 Node.js 的 MongoDB 文档(使用 MongoClient)中从另一个字段附加一个数组字段
- python - 如何将数据从一个类传递到 Scrapy 类
- java - Java 1.8.0_251,OSX Catalina,将字体渲染到屏幕外窗口损坏
- android - 是否可以仅使用约束来定义我的所有布局?
- ios - 撤销当前的 APNs 密钥会破坏实时应用程序吗?
- java - 将 REST 查询参数存储为静态字段
- collision - 与触发器碰撞玩家并让玩家返回主菜单的问题
- coldfusion - CFCHART 整体显示 y 轴数字
- angular - 将 p-table 列的当前页面中的数据传递给另一个应用程序