Setting initial value Angular 2 reactive formarray

ⅰ亾dé卋堺 提交于 2019-12-10 18:17:31

问题


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 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.



来源:https://stackoverflow.com/questions/40875283/setting-initial-value-angular-2-reactive-formarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!