'How to use array of objects inside another array for controls in Reactive Forms

I have the following model:

{
  "name": "Trial",
  "truncatable": false,
  "medias": [
    {
      "url": "justfortest.com",
      "metadata": [
        {
          "name": "metaOne",
          "value": "Metatwo"
        }
      ]
    }
  ]
}

I need to create them in a form group. I'm using it for angular material table its a table inside another table. My try:

  this.form = this.fb.group({
      name: [{value: ''}],
      truncatable: [{value: false],
      medias: this.fb.group({
        url: [{value: false],
        metadata: this.fb.array([])
      })
    });


Solution 1:[1]

For your medias control, use a FormArray instead of a FormGroup and then add FormGroups to it.

Something like this

this.form = this.fb.group({
  name: [{value: ''}],
  truncatable: [{value: false],
  medias: this.fb.array([])
})

for (var i = 0; i < object.medias.length; i++){
  (<FormArray>this.form.get('medias')).controls.push(creationOfFormGroup(object.medias[i]))
}

You must 'cast' your medias control as FormArray to use it as an array.

You can also do like this

...
let medias = this.form.get('medias') as FormArray
for (var i = 0; i < object.medias.length; i++){
  medias.controls.push(creationOfFormGroup(object.medias[i]))
}

creationOfFormGroup() is just a method to return a FormGroup from your medias object.

And then do same thing for metadata values.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alexis