我使用formbuilder创建了一个表单。我尝试将数据数组对象创建为用户对象,但它在用户数组中添加为对象。以下是我的代码
export class AppComponent {
users = [ { "firstname": "ramu", "lastname": "mothukuri", "city": "chennai", "street": "sivan koiil street", "pin": "600024","data":[{"company":"xyz","address":"yyy"}] },
{ "firstname": "ramu", "lastname": "mothukuri", "city": "chennai", "street": "sivan koiil street", "pin": "600024","data":[{"company":"xyz","address":"yyy"}] },
{ "firstname": "ramu", "lastname": "mothukuri", "city": "chennai", "street": "sivan koiil street", "pin": "600024","data":[{"company":"xyz","address":"yyy"}] }
]
myForm: FormGroup;
constructor(private fb: FormBuilder) {
this.myForm = this.fb.group({
users: this.fb.array([])
})
let formArr = <FormArray>this.myForm.controls.users;
formArr.push(fb.group({
firstname: this.users[0].firstname,
lastname: this.users[0].lastname,
street: this.users[0].street,
data:this.users[0].data
}))
}
onMy(form){
console.log(form);
}
}
但我尝试编写代码,但我没有得到以下是json表单值的预期格式
表格值:{
"users": [
{
"firstname": "ramu",
"lastname": "mothukuri",
"street": "sivan koiil street",
"data": [{
"company": "xyz",
"address": "yyy"
}]
}
]
}
以下是代码网址
答案 0 :(得分:2)
您需要将数据声明为formArray
let dataArr = new FormArray([]);
dataArr.push(new FormGroup({
'company': new FormControl(this.users[0].data[0].company),
'address': new FormControl(this.users[0].data[0].address)
}));
let formArr = <FormArray>this.myForm.controls.users;
formArr.push(fb.group({
firstname: this.users[0].firstname,
lastname: this.users[0].lastname,
street: this.users[0].street,
data: dataArr
}));
答案 1 :(得分:0)
在控件数据中的表单组声明中,创建另一个表单组而不仅仅是值。
let formArr = <FormArray>this.myForm.controls.users;
formArr.push(fb.group({
firstname: this.users[0].firstname,
lastname: this.users[0].lastname,
street: this.users[0].street,
data:this.fb.group({
company: this.users[0].data.company,
address: this.users[0].data.address })
}))
}
这样您就可以将数据作为数组获取。