Piotr Kaliński
Piotr Kaliński

Reputation: 227

Angular2 3rd level FormArray nesting,

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>

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());
}

And for some hours, trying everything I got some errors Cannot read property 'push' of null, how to deal with that? I am tired with this, there were several questions but mostly without good reply

Upvotes: 1

Views: 1041

Answers (1)

developer033
developer033

Reputation: 24874

Since lv2 is an Array, you must pass the index from template to component in order to get the lv3 form group related to:

Change your function to:

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

Upvotes: 2

Related Questions