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>

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

0

1 Answer 1

2

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());
}
Sign up to request clarification or add additional context in comments.

3 Comments

Check my html, i might be missing sth.
@PiotrKaliński I can't where you're calling add function.. Anyway, in the second *ngFor do this: let j = index and [formGroupName]="j".
@PiotrKaliński As I said, you must pass the index.. (click)="add(i)"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.