0

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);

2 Answers 2

1

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'});
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for answering. But in my case insert function in working perfectly as: control.insert(i+1, addCtrl);
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.