Setting initial value Angular 2 reactive formarray
Asked Answered
L

1

3

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?

Longcloth answered 29/11, 2016 at 20:34 Comment(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.Tera
S
3

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.

Statued answered 29/11, 2016 at 21:6 Comment(2)
A better solution, in my opinion, would be to iterate over the array to find out how many form groups you need and list them inside a form array which will be the value of your property, in your case 'addresses'. Example here: #42550902Gadmann
@Gadmann In real scenarios like mine a backend service call is required so you don't know in advance the number of elements in the FormArray...Hercule

© 2022 - 2024 — McMap. All rights reserved.