Search code examples
javascripthtmlangularangular4-formsangular5

Angular 5 - Dynamic Row Addition clears the selection in Table


I am new to Angular and I am playing around with Some of the Angular Features. While exploring Two way binding, I have created a Table with dynamic Row addition on the click of a button. I observed that the selection of the other rows gets cleared the moment I add a New Row, after a bit of trial and error, I found out the culprit was <form>and when I removed the tag it was working correctly. I have included the FormModule into the NGModule imports and i still see the same behaviour.

Can someone please explain how do i use table inside a <form> without this error. An explanation of why is this happening is also much appreciated.

Please find my created Plunker below

https://plnkr.co/edit/5YPn88pNOhVoPJA8kSBj?p=preview

Thank you.


Solution

  • Issue is not with the form but the input names

    name should be different,

    What you can do is add index in loop and then change name="soc1" to name="soc1{{i}}"

    Here's the Solution :

    <tr *ngFor="let dat of arr; let i=index;">
        <td>
            <select name="soc1{{i}}" [(ngModel)]="dat.it">
                <option value="PP">PP</option>
                <option value="PQ">PQ</option>
              </select>
        </td>
        <td> <select name="soc2{{i}}{{i}}" [(ngModel)]="dat.bit">
                <option value="PP">PP</option>
                <option value="PQ">PQ</option>
              </select></td>
        <td><button name="Name" (click)="addRow()">Add</button></td>
    </tr>
    

    WORKING DEMO