简体   繁体   中英

Convert JSON to formGroup

I have following JSON data,

{ "page": 2, "per_page": 6, "total": 12, "total_pages": 2, "data": [ { "id": 7, "email": "michael.lawson@reqres.in" }, { "id": 8, "email": "lindsay.ferguson@reqres.in" }, { "id": 9, "email": "tobias.funke@reqres.in" }, { "id": 10, "email": "byron.fields@reqres.in" }, { "id": 11, "email": "george.edwards@reqres.in" }, { "id": 12, "email": "rachel.howell@reqres.in" } ] }

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?

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM