user4676340
user4676340

Reputation:

Reactive Forms : array property being transformed to object

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 ?

Upvotes: 3

Views: 257

Answers (1)

ibenjelloun
ibenjelloun

Reputation: 7713

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.

Upvotes: 5

Related Questions