{
id: 123,
email: "abc@gmail.com",
password: 108,
myObj:[
{ id:1, name:"abc", age: 20 },
{ id:2, name:"def", age: 21 },
{ id:3, name:"ghi", age: 22 },
{ id:4, name:"jkl", age: 23 } ]
}
这就是我从服务器到补丁的字段,我正在修补它们:
this.myForm = this.fb.group({
id: [],
email: [],
password: [],
myObj: []
});
我需要每个myObj
数组作为单独的表单控件。
我尝试以不同方式从HTML访问它们(例如formControlName = myObj[0]
,formControlName = myObj.name
)但没有成功..
如何访问HTML中的myObj
字段?
答案 0 :(得分:1)
它应该是这样的:
objects: any[] = [];
myObj:[
{ id:1, name:"abc", age: 20 },
{ id:2, name:"def", age: 21 },
{ id:3, name:"ghi", age: 22 },
{ id:4, name:"jkl", age: 23 } ]
ngOnInit() {
this.myForm = this.fb.group({
id: [],
email: [],
password: [],
objects: this.formBuilder.array([])
});
this.objects = this.myForm.get('objects') as FormArray;
for(let obj of this.myOj){
this.objects.push(this.createItem());
}
}
createItem(): FormGroup {
return this.formBuilder.group({
id: '',
name: '',
age: ''
});
}
并在模板中:
<div formArrayName="objects"
*ngFor="let item of myForm.get('objects').controls; let i = index;">
<div [formGroupName]="i">
<input formControlName="id">
<input formControlName="name">
<input formControlName="age">
</div>
</div>