首页 > 解决方案 > 如何在不匹配属性名称的情况下在选择中使用对象子作为值

问题描述

我想将选择字段的值设置为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)?

标签: htmlangular

解决方案


尝试像这样实现 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;
  }

推荐阅读