[英]Retrieving data that contains nested arrays in Reactive Forms (FormArray)
我在檢索帶有嵌套數組的數據時遇到麻煩,然后在“反應式表單”中顯示它(第二級數組中的數據被復制)。 問題似乎是我循環數據的方式,但是我不確定該如何解決。 為澄清起見,我在下面有一個示例(該問題出現在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中。
在if語句之前,在for循環內初始化第二個表單數組。 這樣,您可以確保不會將array2值推入相同的形式。
nestedForm: FormGroup;
let array_one = new FormArray([]);
// If an If block to check if 'array1' property is present;
if (this.nestedData['array1']) {
for (let ar1 of this.nestedData.array1) {
let array_two = new FormArray([]); // initialize here
// 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 // but if the data is not available, you will be pushing empty form array here
})
);
}
}
this.nestedForm = this.fb.group({
'nestedOne': [this.nestedData.nestOne],
'array1': array_one
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.