[英]Convert JSON to formGroup
I have following JSON data,我有以下 JSON 数据,
{ "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" } ] }
{ “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,“电子邮件”:“byron.fields@reqres.in”},{“id”:11,“电子邮件”:“george.edwards@reqres.in”},{“id”:12,“电子邮件” :“rachel.howell@reqres.in”}]}
Till now, I have manually created formGroup and assign data in it by using for loop.到目前为止,我已经手动创建了 formGroup 并使用 for 循环在其中分配数据。
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?我不确定,如果我需要手动创建 formGroup 和 formArray,如果我有很长的 json 数据,或者我们有什么可以使用的内置方法?
I tried below, but it gives all controls as formControls, even array is also coming as controls.我在下面尝试过,但它将所有控件作为 formControls,甚至数组也作为控件出现。
this.fb.group(data)
Do we have any existing method which can provide correct formGroup by just passing JSON object?我们是否有任何现有的方法可以通过仅传递 JSON object 来提供正确的 formGroup?
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.