5

I am trying to add a FormArray inside another FormArray but can't figure out how to do it.

I have this in my typescript file:

createForm() {
    this.myForm = this.formBuilder.group({
        people: this.formBuilder.array([
            { addresses: this.formBuilder.array([]) }
        ])
    });
}

Basically, I'm trying to say make a people FormArray where each person can have multiple addresses. I try to render it like this in my html:

<div [formGroup]="myForm">
    <div formArrayName="people">
        <div *ngFor="let person of people.controls; let i=index">
            Person {{ i + 1 }}

            <div *ngFor="let address of person.addresses.controls; let j=index">
                Address {{ j + 1 }}
            </div>
        </div>
    </div>
</div>

Of course, this is just an example and my actual form will have way more going on. I have an "Add person" link that calls a function in my typescript that pushes an object to the people FormArray.

When I call createForm(), I get the following errors in the browser:

ERROR TypeError: this.form._updateTreeValidity is not a function
ERROR TypeError: this.form.get is not a function

What am I doing wrong? How do I accomplish what I want to do? Any help would be appreciated!

1

1 Answer 1

13

Try Something Like this:

stackblitz example

HTML:

<form [formGroup]="myForm" (ngSubmit)="submit()">
    <div formArrayName="people">
        <div *ngFor="let person of getPeople(myForm); let i=index">
            <div style="margin: 5px;" [formGroupName]="i">
                <label>Person {{ i + 1 }}</label>
                <input type="text" placeholder="Name" formControlName="name">
                <button *ngIf="i<1" (click)="addPeople()" type="button">Add People</button>

                <div formArrayName="addresses">
                    <div *ngFor="let address of getAddress(person); let j=index">
                        <div [formGroupName]="j">
                            <span>Address {{ j + 1 }}</span>
                            <input type="text" placeholder="house No" formControlName="houseNo">
                            <input type="text" placeholder="city" formControlName="city">
                            <button *ngIf="j<1" (click)="addAddress(i)" type="button">+</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>

<div style="margin-top: 20px;">
    {{myForm.value | json}}
</div>

TS:

import { Component, OnInit } from '@angular/core';
import { FormArray, FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  survey: FormGroup;
  myForm: FormGroup;
  constructor(private fb: FormBuilder) {

  }

  ngOnInit() {
    this.createForm();
  }

  createForm() {
    this.myForm = this.fb.group({
      people: this.fb.array([this.createPeopleArray()])
    })
  }

  createPeopleArray() {
    return this.fb.group({
      name: null,
      addresses: new FormArray([
        this.createAddressArray()
      ])
    });
  }

  getPeople(form) {
    return form.controls.people.controls;
  }

  getAddress(form) {
    return form.controls.addresses.controls;
  }

  createAddressArray() {
    return this.fb.group({
      houseNo: null,
      city: null
    })
  }

  addPeople() {
    const control = <FormArray>this.myForm.get('people');
    control.push(this.createPeopleArray());
  }

  addAddress(i) {
    const control = <FormArray>this.myForm.get('people').controls[i].get('addresses');
    // console.log(control);
    control.push(this.createAddressArray());
  }

  submit() {
    console.log(this.myForm.value)
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

@UnluckyAj I'm getting the following error: ERROR Error: Cannot find control with path: 'people -> addresses' using your code. Also, I noticed you have addPeople(i), but your function doesn't take any parameters.
its working fine there is no issue in code and i removed 'i' addPeople(i) because no need for that.
Stackblitz link --> The page you requested couldn't be found.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.