【发布时间】:2019-11-20 06:11:38
【问题描述】:
我正在使用表单构建器构建反应式表单。表单数据需要动态更新。为了实现这一点,我创建了一个函数,它迭代对象中的键并使用匹配的键名修补表单值。这在大多数情况下都有效,但是,生成的表单值在值周围有额外的大括号 []。我可能在这里遗漏了一些明显的东西。
这是迭代对象键并修补键名称与表单控件名称匹配的每个值的函数:
/**
*
* @param {object} formGroup form group to update
* @param {object} formValues the form control name as the key and the value to patch
*/
public patchMultipleValues(formGroup, formValues) {
for (let key in formValues) {
let keyToPatch = key;
let valueToPatch = formValues[key];
// Patch value
formGroup.patchValue({ [keyToPatch]: [valueToPatch] });
}
}
这是示例测试数据和测试表单组:
testData = {
'Title': 'Example title',
'Description': 'This is an example description for testing',
'Items': ['A', 'B', 'C', 1, 2, 3]
}
this.testForm = this.fb.group({
Title: [null],
Description: [null],
Items: [null]
});
这是对函数的调用:
this.patchMultipleValues(this.testForm, this.testData);
这是生成的表单值,每个值都带有额外的大括号。 Title 和 Description 应该只是字符串,而 Items 应该只是一个数组。
formGroup.value {"Title":["Example title"],"Description":["This is an example description for testing"],"Items":[["A","B","C",1,2,3]]}
问题:如何更新代码以修补正确的值?我尝试从 this.fb.group 定义中删除大括号,但这不能正常工作。
【问题讨论】:
标签: node.js angular typescript ecmascript-6 single-page-application