添加到Reactive Forms Array Angular的开头 [英] Add to the the beginning of Reactive Forms Array Angular

查看:158
本文介绍了添加到Reactive Forms Array Angular的开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅相关plunker

https://plnkr.co/edit/f0BxpinhuqVz8o6IIFaL?p=preview

  //堆栈溢出让你如果连接了一个plunker就放置代码,但是在这里复制粘贴的代码太多了,只是看起来很乱,所以我只是把这个注释放在这里。 

如果您运行此操作,然后单击添加按钮,则会将新条目添加到数组中,但是表单视图并不反映表单状态,而是第一个条目被复制,最后一个条目不存在。



如果任何人有任何想法或指导,错误我会非常感激,因为我一直在困难的看似简单的任务。



我试图按照官方Angular Reactive Forms指南尽可能接近地构建这个例如。

谢谢

解决方案

好像Angular跟踪您的对象的索引在 formArray 中。这可以通过使用 trackBy 来解决。使用函数将它添加到迭代中:

 < div * ngFor =let detailArray.controls; let i = index ; trackBy:trackByFn[formGroupName] =i> 

和组件:

  trackByFn(index:any,item:any){
return index;

您的 PLUNKER


Please see the relevant plunker

https://plnkr.co/edit/f0BxpinhuqVz8o6IIFaL?p=preview

// stack overflow makes you put code if a plunker is linked but it is too much code to copy paste here it would just look messy so I a am putting this comment instead.

If you run this and then click the add button a new entry is added to the array, but the form view does not reflect the forms state, instead the first entry is duplicated and the last entry is gone.

If anyone has any ideas or guides as to what I am doing wrong I would be very grateful as I have been pretty stuck on a seemingly easy task.

I tried to follow the official Angular Reactive Forms guide as close as possible to build this example.

Thanks

解决方案

Seems like Angular has trouble tracking the index of your objects in your formArray. This can be solved by using trackBy. Add it to your iteration with function:

<div *ngFor="let detail of detailArray.controls; let i=index; trackBy:trackByFn" [formGroupName]="i">

and in component:

trackByFn(index: any, item: any) {
  return index;
} 

Your PLUNKER

这篇关于添加到Reactive Forms Array Angular的开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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