Home » Javascript » javascript – delete particular row in a table

javascript – delete particular row in a table

Posted by: admin February 24, 2020 Leave a comment

Questions:

i just started with angular.i checked few links stackoverflow links but none worked in my case.i have table where i am adding rows dynamically and i also need to delete rows dynamically but my code deleting rows from the last row even i am clicking delete button of some other row.i used below code and i am giving stackblitz link below. thanks in advance.

  rows = [1];
    
addrows() {
      this.rows.push(1);
 }

deleterow(row){
  this.rows.splice(row, 1);
}
 <table>
 <tr *ngFor="let row of rows;">
 <td> something</td>
 <td> something</td>
 <td> something</td>
 <td>
      <button class="btn btn-danger" (click)="deleterow(i)">Delete</button>
 </td>
<tr>
<table>
<div class="text-center">       
      <button class="btn btn-primary" (click)="addrows()">ADD more rows</button>
</div>

stackblitz link

How to&Answers:

You need to use the row’s index to splice the row. You are currently just hoping that a variable i gets magically created.

In my solution’s component.ts, I am going to allow my HTML to add to and delete from a simple array.

component.ts

counter: number = 0;

rows = [];

addRow() {
  this.counter++;
  this.rows.push(this.counter);
}

deleteRow(row: number) {
  this.rows.splice(row, 1);
}

The key to the deleteRow function is that you need access to the current index within *ngFor. For that, you can use let i = index within the *ngFor to store the current index in a variable i.

component.html

<table>
  <tr *ngFor="let row of rows; let i = index">
    <td>{{row}}</td>
    <td><button (click)="deleteRow(i)">Delete row</button></td>
  </tr>
</table>

<button (click)="addRow()">Add row</button>

DEMO: https://stackblitz.com/edit/angular-7uwuye

Answer:

Javascript

deleterow(id){
document.getElementById("row"+id).remove();
}

HTML

<td id="row1">
<button class="btn btn-danger" onclick="deleterow(1)">Delete</button>
</td>