将值分配给FormGroup并推入FormArray-反应性表单

时间:2019-08-02 14:02:48

标签: angular angular-forms

考虑如下所示的表单组:

userDetail = new FormGroup({
   name: new FormControl(''),
   addresses:new FormArray([])
})

addressDetail: new FormGroup({
  city: new FormControl(''),
  country:new FormControl('')
})

我从API获得的响应如下:

{
  name:"Gayathri",
  addresses:[{
               city:"Chennai", 
               country:"India"
              },{
               city:"Mumbai", 
               country:"India"
              }
}

我现在要尝试的是将地址中的每个对象分配给addressDetail表单组,并将这些表单组推送到formarray。以下方法失败,并且不确定为什么会失败。

方法1: 考虑res是包含API响应的对象:

this.userDetail.patchValue(res) //addresses is blank
 res.addresses.foreach((address)=>{
       this.addressDetail.patchValue(address);
       (<FormArray>this.userDetail.get('addresses')).push(this.addressDetail)
   })
 console.log(this.userDetail.value) //all the two records be city mumbai and country India

方法2: 考虑res是包含API响应的对象:

  res.addresses.foreach((address)=>{
          (<FormArray>this.userDetail.get('addresses')).push(this.addressDetail) //assume formGroup is pushed to formarray
       })
 this.userDetail.patchValue(res) //contains addresses
console.log(this.userDetail.value) //all the two records in addresses be city mumbai and country India

请让我知道发生了什么问题以及如何解决。

1 个答案:

答案 0 :(得分:0)

您可以尝试

export class AppComponent implements OnInit {
  name = 'Angular';
  userDetail = new FormGroup({
    name: new FormControl(''),
    addresses: new FormArray([])
  })

  addressDetail = new FormGroup({
    city: new FormControl(''),
    country: new FormControl('')
  });

  value = {
  name:"Gayathri",
  addresses:[{
               city:"Chennai", 
               country:"India"
              },{
               city:"Mumbai", 
               country:"India"
              }
]};

  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.userDetail.patchValue(this.value);
    const addressesFG = this.value.addresses.map(address => {
      return this.fb.group({
        city: [address.city],
        country: [address.country],
      })
    });
    const addressesFormArray: FormArray = this.fb.array(addressesFG);
    this.userDetail.setControl('addresses', addressesFormArray);
    console.log(this.userDetail);
  }


}

一堆https://stackblitz.com/edit/angular-myamrb