简体   繁体   English

Angular 5 反应形式 - 带有 FormArray 的 patchValue 不起作用

[英]Angular 5 reactive form - patchValue with FormArray not working

I have this reactive form in the Ionic3 framework, which I need to populate with data I retrieve from API.我在 Ionic3 框架中有这个反应形式,我需要用我从 API 检索到的数据填充它。 To do so I am using patchValue as I read somewhere that it is more reliable than setValue .为此,我正在使用patchValue因为我在某处读到它比setValue更可靠。

The problem I am facing is, it does not populate repeated form fields.我面临的问题是,它不会填充重复的表单字段。 To explain better I've created this example code .为了更好地解释,我创建了这个示例代码

I have tried other ways around like directly assigning data to the respective field instead of using for loop first, but that only populated 1 set instead of all 3.我尝试了其他方法,比如直接将数据分配给相应的字段,而不是先使用for循环,但只填充了 1 个集合而不是全部 3 个。

Can someone point out what I am doing wrong, or provide a better solution?有人可以指出我做错了什么,或者提供更好的解决方案吗?

Thank you谢谢

In your example set your for loop on the home component to look like this在您的示例中,将 home 组件上的 for 循环设置为如下所示

for(const rooms of resp.room_data){

      const roomNumberControl = this.createRooms();
      (<FormArray>this.informationForm.controls.room_numbers).push
      (roomNumberControl);
      console.log(JSON.stringify(rooms));
    }

Create rooms would just need to have some data in them but that will create on object for everyone in the array.创建房间只需要在其中包含一些数据,但这将为数组中的每个人创建对象。 This is how I have done it in the past.这就是我过去所做的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM