我需要在表单中添加嵌套字段。我完全按照这个教程http://brophy.org/post/nested-reactive-forms-in-angular2/进行操作。
虽然一切对我来说都工作正常,但我需要添加按钮与每个 child 一起,并单击将 child 添加到它们之间。
例如:如果有
child1 添加 btn child2 添加按钮 child3 添加按钮 child4 添加 btn
现在,如果单击 child2 的 add-btn,则新字段应插入到 child2 之后。
我尝试过:在 for 循环中使用标签,如下所示,它显示添加按钮,但单击该新字段总是在末尾插入,这是不需要的。
<a href="" (click)="addChild()">
Add Child
</a>
我的想法:我可以在 add 函数中传递如下所示的 id,然后插入到该索引处的数组中。但不幸的是不知道如何做到这一点。
(click)="addChild(idx)";
希望它是清楚的。请告诉我是否可以使用这种方法实现所需的效果。提前致谢。
答案:毕竟我关注了https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2 .. 并通过 -
解决control.insert(i+1, addCtrl);
最佳答案
只需存储 ngFor 循环的索引,如下所示:
<div *ngFor="let item of items; let i = index;">
{{item.name}}
<a href="" (click)="addChild(i)">
Add Child
</a>
</div>
变量 i 现在将存储每个项目的索引,并且在按钮单击事件中,该项目的索引将作为参数发送到 addChild() 方法。然后,您可以将新项目添加到组件中的该位置:
export class FieldsComponent {
items: Array<any> = [
{name: 'item1'},
{name: 'item2'},
{name: 'item3'},
{name: 'item4'}
];
addChild(index: number): void {
//Insert after the index of the clicked button
items.splice(index + 1, 0, {name: 'Added item'});
}
}
关于javascript - 如何使用单独的添加按钮在 IONIC2/Angular2 表单中添加嵌套字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45498903/