繁体   English   中英

在 Angular 的反应式表单上使用对象时,为什么不能以编程方式设置选择选项

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

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

那是我的课

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[] = [];

slotStatusTypesList 变量由另一个 HTTP GET 调用填充。

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

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

在一个回调函数中填写slotForm表单,其中找到对应的值后的主题字段,如下所示:

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表单选择未按照我的预期设置为选定的值。
为什么在这种情况下不起作用?

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM