2017-05-03 107 views
1
createForm() { 
    this.myForm = this.fb.group({ 
     name: '', 
     lvl2: this.fb.array([ 
      this.initLvl2(), 
     ]) 
    }) 
} 

<form [formGroup]="myForm" novalidate> 
<div formArrayName="lvl2"> 
    <div *ngFor="let lvl2s of myForm.controls.lvl2.controls; let i=index let last=last"> 
     <div class="panel-body" [formGroupName]="i"> 
       <div *ngFor="let lvl3 of lvl2s.controls.lvl3.controls; let i=index let last=last" formArrayName="lvl3"> 
        <div class="panel-body" [formGroupName]="i"> 
           <div class="margin-20"> 
             <button md-raised-button type="button" *ngIf="last" (click)="add()" style="cursor: default">Add Action</button> 
            </div> 
        </div> 
       </div> 
     </div> 
    </div> 

Angular2 3級FormArray嵌套,

initLvl2() { 
    return this.fb.group({ 
     name: '', 
     lvl3: this.fb.array([ 
      this.initLvl3() 
     ]) 
    }) 
} 

initLvl3() { 
    return this.fb.group({ 
     parameters: '', 
     wait_time: '' 
    }) 
    } 

    add(){ 
    const control = <FormArray>this.myForm.get('lvl2.lvl3') 
    control.push(this.initLvl3()); 
} 

而幾個小時,亂投醫我得到了一些錯誤 無法讀取屬性「推」空的,如何處理呢?我厭倦了這一點,有幾個問題,但大多沒有很好的答覆

回答

1

由於lv2Array,必須從模板通過指數到組件,以獲得有關lv3表單組:

將您的function更改爲:

add(index: number): void { 
    const arr: FormArray = this.myForm.get(`lvl2.${index}.lvl3`) as FormArray; 
    arr.push(this.initLvl3()); 
} 
+0

檢查我的html,我可能會缺少某事。 –

+1

@PiotrKaliński我不能在你打電話的地方* add *'function' ..無論如何,在第二個'* ngFor'這樣做:'let j = index'和'[formGroupName] =「j」'。 – developer033

+0

@ developer003忘了粘貼,仍然無法正常工作。 –