【发布时间】: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{}。