Convert JSON to formGroup

2.8k Views Asked by At

I have following JSON data,

{
  "page": 2,
  "per_page": 6,
  "total": 12,
  "total_pages": 2,
  "data": [
    {
      "id": 7,
      "email": "[email protected]"
    },
    {
      "id": 8,
      "email": "[email protected]"
    },
    {
      "id": 9,
      "email": "[email protected]"
    },
    {
      "id": 10,
      "email": "[email protected]"
    },
    {
      "id": 11,
      "email": "[email protected]"
    },
    {
      "id": 12,
      "email": "[email protected]"
    }
  ]
}

Till now, I have manually created formGroup and assign data in it by using for loop.

  result1 = new FormGroup({
    page: this.fb.control(''),
    total: this.fb.control(''),
    data: this.fb.array([])
  });

  this.getUsersWithoutFormGroup().subscribe((data: pageData) =>{
    let users = this.result1.get('data') as FormArray
    data.data.forEach(element => {
      users.push(this.fb.group({
          id: [element.id],
          email: [element.email]
        })
      ) 
    });
  })

I am not sure, if I need to create formGroup and formArray manually, if I have long json data, or we have any inbuilt method which I can use?

I tried below, but it gives all controls as formControls, even array is also coming as controls.

this.fb.group(data)

Do we have any existing method which can provide correct formGroup by just passing JSON object?

1

There are 1 best solutions below

2
Juan Vicente Berzosa Tejero On

Try this:

this.result1.value = [...data];

Know I'm not sure if we can change a form directly assigning its value, so if the above did'nt work, try this in this way:


if (data != null) {
   this.result1.patchValue(data);
}

EDIT:

if (data != null) {
   this.result1.patchValue(data);
   this.result1.patchValue(
      { data: data.data }
   );
}