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

我很高興它爲你工作。你現在可以接受我的答案.. –

相關問題