3

The issue can be seen in this stackblitz :

I have a payload :

payload = {
  id: 1,
  name: 'This is the payload',
  children: [
    { id: 1, name: 'Child 1' }
  ],
};

I create a form group out of that :

this.form = this.fb.group(this.payload);

I then display the value of the form :

{{ form?.value | json }}

And the result is :

{ "id": 1, "name": "This is the payload", "children": { "id": 1, "name": "Child 1" } }

As you can see, the children property went from an array, to an object.

  1. How did that happen ?
  2. Is it possible to stop Angular from doing that ?
  3. If I need to use a formArray, is there a way to make it automatic ?

1 Answer 1

5

You should declare an array of array, as group takes array as argument [value, ...validators] :

payload = {
    id: 1,
    name: 'This is the payload',
    children: [[
      { id: 1, name: 'Child 1' },
    ]],
  };

To declare an array value according to angular.io :

this.fb.group({
   anArray: [[]]
});

// OR
this.fb.group({
   anArray: this.fb.array([])
});

// OR
this.fb.group({
   anArray: new FormControl([])
});

If you want to make dynamic forms, have a look at this angular.io page.

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

3 Comments

Thank you, so this brings the question, is there a way to automatically create a double array (or fb.array) from a simple array ? Or do I have to iterate over every property and test if it's an array, then change it to double array ?
The angular.io link I've shared in the post, explains that for dynamic forms, you could create a YourModelControlService that will transform an object to form group. In your case, you will need to identify if it's an array and use fb.array in the toFormGroup function.
Didn't see the link, thank you ! I'm going home now, but I will definitely look at it when I come back on Monday.