3
votes

I am trying to set the initial value for an angular 2 reactive form formArray object.

Even though the json object used to set the form value contains an array value with multiple entries, only the first entry is shown and the "form.value" also only shows the first entry.

I am using the syntax (<FormGroup>this.myForm).patchValue(value, { onlySelf: true }); to set the initial value on the form.

Here is a plunker demonstrating the issue: https://plnkr.co/edit/j1S80CmPBF1iHI5ViEia?p=preview

I used the example from https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2 to create the plunker.

Any ideas what I've done wrong?

1
You've initialized the form myForm with the FormArray that consists of one FormGroup. I assume this is the reason another address gets ignored.Daniel Mylian

1 Answers

3
votes

You are setting addresses as an array of forms and in initAddress() method you are only returning one element. If you add a second call to the addresses array you get the second address.

this.myForm = this._fb.group({
  name: ['', [Validators.required, Validators.minLength(5)]],
  addresses: this._fb.array([
    this.initAddress(),
    this.initAddress()
  ])
});

It sounds kind of stupid but it will return the element positioned in the array and if you exceed the amount of elements in the array you will get an empty one.

Hope it helps.