Reputation: 727
I am in need to add nested fields in a form. I followed exactly this tutorial http://brophy.org/post/nested-reactive-forms-in-angular2/.
Although every thing is working fine for me, except that I need the add button to be with every child and on clicking on which the child is added in between them.
ex: if there are
child1 add-btn child2 add-btn child3 add-btn child4 add-btn
now if add-btn of child2 is clicked then the new field should be inserted after child2.
I tried: using a tag in for loop as below it shows add button but on clicking that new field is inserted at end always that is not desired.
<a href="" (click)="addChild()">
Add Child
</a>
What I think: That I can pass id as below in add function and then insert into an array at that index. But unfortunately not getting how to do that.
(click)="addChild(idx)";
Hope it's clear. Please let me know if I can achieve the desired using this approach. Thanks in advance.
Answer: After all I followed https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2 .. and solved by -
control.insert(i+1, addCtrl);
Upvotes: 0
Views: 46
Reputation: 727
After all I followed https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2 .. and solved by -
control.insert(i+1, addCtrl);
Hope it will help someone.
Upvotes: 0
Reputation: 1050
Just store the index of the ngFor loop like this:
<div *ngFor="let item of items; let i = index;">
{{item.name}}
<a href="" (click)="addChild(i)">
Add Child
</a>
</div>
The variable i will now store the index of each item, and on button click events the index of the item will be sent as a parameter to the addChild() method. You can then add an new item to that position in your component:
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'});
}
}
Upvotes: 1