1

I am creating a dynamic table which adds a row on click(). However, every add of the row resets the value of the previous row.

<tfoot>
   <tr>
       <td><button type="button" (click)="addRow()">Add row </td>
   </tr>
</tfoot>

// html

<tbody>
    <tr *ngFor="let row of rows">
        <td><input name="something" type="text" [ngModel]="row.item.name </td>
    </tr>
</tbody>

// component

...
this.item = {name: 'Superman'};

this.rows = [{
    item: this.item
}];

....
this.addRow() {
    this.rows.push({
        item: this.item
    });
}

2 Answers 2

1

[SOLVED] We just need to make the name of the input unique!

<tfoot>
   <tr>
       <td><button type="button" (click)="addRow()">Add row </td>
   </tr>
</tfoot>

// html
<tbody>
    <tr *ngFor="let row of rows; let i = index">
        <td><input name="something_{{i}}" type="text" [ngModel]="row.item.name </td>
    </tr>
</tbody>

// component
...
this.item = {name: 'Superman'};

this.rows = [{
    item: this.item
}];

....
this.addRow() {
    this.rows.push({
        item: this.item
    });
}
Sign up to request clarification or add additional context in comments.

Comments

0

Because you're pushing same object reference in an array multiple times. So if you change this.item will effectively change the value in all newly added array element(since they carry the same object reference).

The solution would be, push clone object to an items array.

this.rows.push({
    item: Object.assign({}, this.item); //created clone
});

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.