我需要根据任何对象(来自api)构建一个表单组。是否可以将该对象直接分配给表单组?
例如,这是对象,
parent: 'All', value: 1, children: [
{
parent: 'Programming', value: 91, children: [
{
parent: 'Frontend', value: 911, children: [
{ parent: 'Angular 1', value: 9111 },
{ parent: 'Angular 2', value: 9112 },
{ parent: 'ReactJS', value: 9113, disabled: true }
]
},
{
parent: 'Backend', value: 912, children: [
{ parent: 'C#', value: 9121 },
{ parent: 'Java', value: 9122 },
{ parent: 'Python', value: 9123, checked: false, disabled: true }
]
}
]
},
{
parent: 'Networking', value: 92, children: [
{ parent: 'Internet', value: 921 },
{ parent: 'Security', value: 922 }
]
}
]
}
最后,所需的表单组应该是这样的,
form: {
"username": "",
"password": "",
"treeView": {
"All": null,
"children": [
"programming": "",
"children": ["Angular 1": "","Angular 2": "", "ReactJS": "" ]
]
}
}
答案 0 :(得分:0)
是的,你可以这样做。需要使用formBuilder.array
childArr : FormArray;
this.form = this.formBuilder.group({
"username": "",
"password": "",
"treeView": this.formBuilder.group({
"All": null,
"children": this.childArr;
})
});
您可以使用此行推送您的对象
此行将您的响应循环。
(<FormArray>this.form.get('children')).push(new FormControl(obj))