【发布时间】:2020-11-19 06:17:25
【问题描述】:
我想弄清楚,因为我无法使用以下打字稿代码设置反应式表单的选择选项:
这是我的课
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 表单选择没有像我预期的那样使用所选值设置。
为什么在这种情况下它不起作用?
【问题讨论】:
标签: angular typescript angular-reactive-forms