为什么在 Angular 中使用响应式表单上的对象时无法以编程方式设置 select 选项

Why can't I set a select option programmatically when using an object on a Reactive Form in Angular

我想弄清楚,因为我无法使用以下打字稿代码设置反应式表单的 select 选项:

那是我的class

export class SlotStatusTypes {
    id: number;
    description: string;
}

这是我的组件模板

<select id="subject" formControlName="subject" class="form-control"
   aria-describedby="subject">
   <option *ngFor="let statusType of slotStatusTypesList" [ngValue]="statusType">
      {{statusType.description}}
   </option>
</select>

这在我的组件中:

slotStatusTypesList: SlotStatusTypes[] = [];

The slotStatusTypesList variable is filled in by another HTTP GET call.

在这里我初始化我的表单:

ngOnInit(): void {
   this.slotForm = new FormGroup({
      ...
      subject: new FormControl(null, [
        Validators.required
      ]),
      ...
   });
}

在回调函数中填写slotForm表单,其中subject字段找到对应的值后如下图:

let statusTypeFound: SlotStatusTypes = this.slotStatusTypesList.find(r => r.id === slotPlanning.statusTypeId);

this.slotForm.setValue({
   ...
   subject: statusTypeFound,
   ...
});

到目前为止一切正常。

现在,我想在 slotForm 表单中设置一个相同类型的 SlotStatusTypes 对象,而不是通过列表查找对象,见下文:

let slotStatusType: SlotStatusTypes = {
   id: slotPlanning.id, //id: 1
   description: slotPlanning.description //description: "Available"
};

this.slotForm.setValue({
   ...
   subject: slotStatusType,
   ...
});

此时 slotForm 表单 select 没有像我预期的那样设置 selected 值。
为什么在那种情况下它不起作用?

我相信你的问题就在这里,在创建新的 slotStatusType 对象时。

let slotStatusType: SlotStatusTypes = {
   id: slotPlanning.id,
   description: slotPlanning.description
};

这是一个带有新引用的新对象,slotStatusTypesList 数组中不存在。因此 select 无法匹配列表中的任何项目与 slotStatusType,尽管属性 iddescription 相同。

FormControlsetValue 您需要使用 slotStatusTypesList 数组中的项目。我不确定您是否可以避免搜索它,但您可以优化代码以在找到项目后保存对项目的引用。