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

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

问题描述

我正在尝试为 angular 2 反应形式 formArray 对象设置初始值.

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

即使用于设置表单值的 json 对象包含具有多个条目的数组值,也只显示第一个条目,form.value"也仅显示第一个条目.

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.

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

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

这是一个演示该问题的 plunker:https://plnkr.co/edit/j1S80CmPBF1iHI5ViEia?p=预览

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

我使用了 中的示例https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2 来创建 plunker.

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

知道我做错了什么吗?

推荐答案

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

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.

希望有帮助.

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

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