Angular2 patchValue JSON data to formArray

patchValue only updates the existing FormArray, it won't modify the structure of your FormArray. You have to make sure your FormArray is of the right size before patching it, you can also recreate it completely, as shown below:

this.data.patchValue({ name: data.name, age: data.age });

this.data.controls['address'] = this.FB.array(data.map(address => {
    const group = this.addAddress();
    group.patchValue(address);
    return group ;
}));

See this post for more details.


If you were not to have a FormArray in your form, you could just use this.data.patchValue(data) (or setValue if all properties match), but since you have a formarray, you need to iterate your address array in your object and push formgroups to your formarray. Also I see no need to initially create an empty formgroup when building the form, so I have left it out:

ngOnInit() {
  this.data = this.FB.group({
    name: [''],
    age: [''],
    address: this.FB.array([])
  })
}

get formArr() {
  return this.data.get('address') as FormArray;
}

// ....
this.data.patchValue({name: data.name, age: data.age});
data.address.forEach((x) => {
  this.formArr.push(this.FB.group(x))
});