How can i access FormArray inside formGroup inside another formGroup?

Viewed 114

I have an array of data as follows:

[
    {
      id: "1",
      name: "task1",
      taskForms: [
        {
          id: "8782",
          name: "ProcedureComment",
          sortOrder: null,
          description: "Comment for 'Procedure end / Suture' task",
          label: null
        },
        {
          id: "20",
          name: "form20",
          description: "form20 description",
          label: "form20 lable"
        }
      ]
    },
    {
      id: "2",
      name: "task2",
      taskForms: [
        {
          id: "87822",
          name: "ProcedureComment2",
          sortOrder: null,
          description: "Comment for 'Procedure end / Suture' task2",
          label: null
        },
        {
          id: "202",
          name: "form202",
          description: "form202 description",
          label: "form202 lable"
        }
      ]
    }
  ];

and I want to convert taskForms to FormArray().

Do I have to mark tasks as formGroup and then mark taskForms as FormArray? How do I do this?

public formGroup = new FormGroup({
    tasks: new FormControl([]) 
//==>> i need it first as FormControl then i want to convert it and write data inside.
  });

I tried:

    this.formGroup.setControl('tasks', this.formBuilder.group(tasks));

but I couldn't make it work.

1 Answers

FormArray in Nested FormGroup

You can just use the FormBuilder to make your life easier:

constructor(private fb: FormBuilder) {}

ngOnInit(): void {
  this.formGroup = this.fb.group({
    nested_formgroup: this.fb.group({
      array: this.fb.array([
        { example: ['']}
      ])
    })
  })
}

Result

{
  "nested_formgroup": {
    "array": [
      {
        "example": ""
      }
    ]
  }
}

Load the Data

To load the data you will just need to map your object to the value members of the FormControls.

loadData() {
  this.someService.getData().subscribe(
    data => {
      this.formGroup.get('nested_formgroup').get('array').value[0].example = data.example
    }
  )
}

Here's an example on Stackblitz for you to test/play with.

Related