1

I have json file that has array of organizations and each organization object has its properties and array of regions as well. I am building reactive angular form with pre-populated values in it as shown below.

public createForm() {
  this.editForm = this.fb.group({
   organizations: this.fb.array(
     [this.buildOrganization('text')]
   )
  });
 }

 buildOrganization(name: String) {
    return new FormGroup({
      organizationTitle: new FormControl(name),
      regions: this.fb.array(
        [this.buildRegion()]
      )
    })
 }

 buildRegion() {
    return new FormGroup({
      regionTitle: new FormControl(''),
    })
 }

I am trying to add one static value "text", but lets say I have an array of organizations, how can I pre-populate this form?

screen shot of example json format. Here I only need description from both organization(s) and region(s) object(s)

enter image description here

4
  • Does it work with the static value? Commented Apr 4, 2018 at 21:16
  • I am trying to show value in input box in html and it shows. Commented Apr 4, 2018 at 21:18
  • Please post the example json file used for populating the form. Commented Apr 4, 2018 at 21:18
  • I have updated question with snapshot. I only need description of both organization(s) object and for region object(s) Commented Apr 4, 2018 at 21:22

1 Answer 1

1

I am trying to add one static value "text", but lets say I have an array of organizations, how can I pre-populate this form?

screen shot of example json format. Here I only need description from both organization(s) and region(s) object(s)

TL;DR WORKING STACKBLITZ


You need to loop over the data and dynamically call the buildOrganization and the buildRegion instead of binding data statically.

The methods could be modified like below:~

  public createForm() {
    this.service.getOrgData().subscribe(response => {
      this.orgData = response;
      this.editForm = this.fb.group({
        organizations: this.fb.array(
          this.orgData.organisations.map(org => this.buildOrganization(org))
        )
      });
    });
  }

  buildOrganization(org: any) {
    return new FormGroup({
      organizationTitle: new FormControl(org.description),
      regions: this.fb.array(
        org.regions.map(region => this.buildRegion(region))
      )
    });
  }

  buildRegion(region) {
    return new FormGroup({
      regionTitle: new FormControl(region.description)
    });
  }

This is the way to prepopulate a nested dynamic reactive form with nested form-arrays.

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

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.