对象数组的表单控件

时间:2018-05-24 06:45:27

标签: html angular typescript primeng

{ 
    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字段?

1 个答案:

答案 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>