2017-11-18 143 views
0

我无法检索与嵌套数组数据,然后在我的反应形式显示它嵌套的数组中检索数据(第二级阵列中的数据被复制)。这个问题似乎是我循环数据的方式,但我不知道该如何解决它。为了说明我在下面有一个例子(问题出现在array2属性中)。包含在无窗体(FormArray)

原始数据对象

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,同时将其保存在其父数组1中。

回答

0

如果语句之前只是初始化循环内的第二种形式排列。通过这样做,你要确保你不会推数组2值转换成相同的形式。

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 
}); 
+0

谢谢你!我一直在努力与这个问题一段时间了,从来没有意识到的问题是在代码我把我的array_two变量。 –

+0

我很高兴它为你工作。你现在可以接受我的答案.. –