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

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

问题描述

请看相关plunker

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

如果链接了plunker,则堆栈溢出会使您放置代码但是复制粘贴在这里的代码太多了看起来很乱,所以我把这个评论改为.

如果你运行这个然后点击添加按钮,一个新的条目被添加到数组中,但表单视图不会反映表单状态,而是第一个条目被复制而最后一个条目消失了.

如果有人对我做错了什么有任何想法或指导,我将非常感激,因为我一直被困在一个看似简单的任务上.

我尽量按照官方的 Angular Reactive Forms 指南来构建这个示例.

解决方案

似乎 Angular 无法跟踪 formArray 中对象的索引.这可以通过使用 trackBy 来解决.使用函数将其添加到您的迭代中:

在组件中:

trackByFn(index: any, item: any) {回报指数;}

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

解决方案

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天全站免登陆