我的API响应是这样的
"groups": [{
"group_name": "GRP1"
"attributes": [{
"attribute_id": 1,
"attribute_name": "Frequency",
"value_reference": "tag"
}]
},
{
"group_name": "GRP2"
"attributes": [{
"attribute_id": 2,
"attribute_name": "Date",
"value_reference": "static",
"value_static_type": "date"
}]
}]
- 我如何在Angular 4中创建formConrol来显示数据
GroupName
List of Group's Attribute
GroupName
List of Group's Attribute
我的初始表单控件就像
this.editTemplateForm = this.fb.group({
groups: this.fb.group({
group_name: ['', Validators.required ],
attributes : this.fb.group({
value_reference : []
})
}),
});
我不明白如何动态添加控件
1 回答
如果您想要完全匹配您的API响应,那么此处的结构最终会相当复杂 . 由于到目前为止,每个
attributes
属性只有一个属性对象,因此可能直接使attributes
成为对象而不是对象数组,这将简化以下代码 . 下面的代码与您当前的API结构相匹配,可以在this working plunker播放 .要注意的一些事项:
FormGroup
需要是最外层的表单对象,也可用于保存不确定数量的FormControl
项另一方面,当控件的数量不确定时,
FormArray
非常有用, and 这些控件的调用并不重要 .这就是为什么,下面,
allGroups
是一个包含最大组的数组,而attributes
是一个包含属性对象的数组,但这些属性对象本身就是组 - 因为我们希望能够根据它们的API属性名来命名控件你确实希望所有这些值都是可编辑的
<input>
字段,但它应该为你提供一个强大的基础来使用plunker,并了解如何根据更改的表单对象动态生成HTML .