【问题标题】:How to use object child as value in select without matching property name如何在不匹配属性名称的情况下在选择中使用对象子作为值
【发布时间】:2020-02-26 23:18:02
【问题描述】:

我想将选择字段的值设置为repairData 属性中指定的值,称为reportShiftId,但它不起作用。另一方面,如果我在 repairData 中创建 Shift 对象并用 reportShift.id 引用它,它就可以工作。

当我更改 repairData.reportShiftId 这是 select 的 ng 模型时,在不工作的代码中,select 选项不会改变,但是当我在 select 中手动选择某些内容后,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(number) 代替reportShift.id(Shift.number)?

【问题讨论】:

  • 组件是否应用了ChangeDetectionStrategy.onPush,问题中演示了哪个模板?
  • 我是 Angular 新手。我认为不是。它只是由 Visual Studio 代码插件“Angular Files”生成的普通组件。
  • 未提供问题的原因。我只是试图猜测出了什么问题。 component.ts 文件中是否有 ChangeDetectionStrategy 代码段?
  • 它应该在 @Component({... here... }) 配置中。如果是 - 尝试删除它。应该可以解决您的问题
  • 不,它只有选择器、templateUrl 和 styleUrls 我从未在任何组件中更改过@component{}。

标签: html angular


【解决方案1】:

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

【讨论】:

  • 检查这个 stackBlitz stackblitz.com/edit/angular-afr8kd
  • 如果我想为整个模型实现选择,而不仅仅是 Id,将默认 compareWith 函数更改为自定义函数会很有帮助。
  • 在 stackblitz 上它可以工作,但如果我将它粘贴到我的应用程序它不会,但我想出了如何让它工作。
  • 很高兴能帮上忙
【解决方案2】:

我知道问题出在哪里。 在我将name html 属性从 shift 更改为 reportShift (与对象属性同名)后,它开始工作了。

实际上,我认为我有不止一个选择具有相同的 name,所以这可能是问题所在。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-10
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多