我有一个服务调用 API 来填充选择下拉列表。当我选择一个选项时,我的 OnChange 方法将从正在调用的另一个服务检索数据。然后该数据将显示在 UI 上。数据显示正常,但如果我想更改某些内容,字段不会更新。现在我正在 forEach 内部使用推送控件来获取数据。
const infoTemp = this.tempInfo?.customFields?.textCustomFields;
infoTemp.forEach((res) => {
this.customNameFormArr.push(
this.fb.group({
name: [res.name],
value: [res.value],
})
);
});
我非常确定我必须使用 patchValue 才能编辑字段。我已经尝试过这段代码,但它似乎不起作用。有什么想法吗?
this.envelopeRequest.controls.newRequest.patchValue({
customFields: {
textFields: [
{
name: res.name,
value: res.value
}
]
}
})
这是我的 StackBlitz 演示的链接。谢谢。演示
在 HTML 中,您将值与
value
属性绑定。
<input type="text" value="{{ t.value }}" />
相反,您需要应用
formControlName
属性来利用 Reactive Form(方式),因此它将反映该值。
<input type="text" formControlName="value" />
对于第二个问题,我注意到更改选项时,
FormArray
(s)将保留上一个(所选)选项的值。在与新选择的选项的值绑定之前,您没有正确重置/清除 FormArray
中的项目。
this.customNameFormArr.clear();
this.customTextFormArr.clear();