设置初始值Angular 2反应性formarray [英] Setting initial value Angular 2 reactive formarray

查看:383
本文介绍了设置初始值Angular 2反应性formarray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



尽管用于设置表单值的json对象包含一个数组值有多个条目,只显示第一个条目,form.value也只显示第一个条目。



我使用的语法 (< FormGroup> this.myForm).patchValue(value,{onlySelf:true}); 设置表单的初始值。

这是一个展示问题的闯入者: https://plnkr.co/edit/j1S80CmPBF1iHI5ViEia? p =预览



我使用 https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2 a>创建plunker。



任何想法我做错了吗?

解决方案

您将地址设置为一个表单数组,并在 initAddress()方法你只返回一个元素。
如果您向地址数组添加第二个调用,您将获得第二个地址。

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

这听起来很愚蠢,但它会返回位于数组中的元素,并且如果超过了数量的数组中的元素,你会得到一个空的。



希望它有帮助。


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?

解决方案

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.

这篇关于设置初始值Angular 2反应性formarray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆