【发布时间】:2017-11-18 19:13:26
【问题描述】:
我无法使用嵌套数组检索数据,然后在我的响应式表单中显示它(第二级数组中的数据被重复)。问题似乎是我循环数据的方式,但我不确定如何修复它。为了澄清,我在下面有一个例子(问题出现在 array2 属性上)。
原始数据对象
nestedData = {
nestOne: "Level One",
array1: [
{
nestTwo: "A",
array2: ["Tag A"]
},
{
nestTwo: "B",
array2: ["Tag B"]
}
]};
下面是响应式代码
nestedForm: FormGroup;
let array_one = new FormArray([]);
let array_two = new FormArray([]);
// If an If block to check if 'array1' property is present;
if (this.nestedData['array1']) {
for (let ar1 of this.nestedData.array1) {
// IF BLOCK FOR array2
if (ar1['array2']) {
// For loop to get array2 data
for (let ar2 of ar1.array2) {
array_two.push(
new FormControl(ar2, Validators.required),
)
}
} //IF Block Ends
array_one.push(
new FormGroup({
'nestTwo': new FormControl(ar1.nestTwo),
'array2': array_two
})
);
}
}
this.nestedForm = this.fb.group({
'nestedOne': [this.nestedData.nestOne],
'array1': array_one
});
现在查看结果如下:
{{nestedForm.value | json}}
{
"nestedOne": "Level One",
"array1": [
{
"nestTwo": "A",
"array2": [
"Tag A",
"Tag B"
]
},
{
"nestTwo": "B",
"array2": [
"Tag A",
"Tag B"
]
}
}
如您所见。标记 A 和标记 B 不应该出现在两个 array2 属性中。我不知道检索 array2 数据然后将其推送到 Reactive FormArray 的最佳方法,同时将其包含在其父 array1 中。
【问题讨论】:
标签: javascript arrays angular angular-reactive-forms