Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular, delete a row from html-table by ID

This time i need help about how to delete a row based the row ID in html-table when delete button clicked. The table data source is from a separated Json file.

The table looks like this : Image Link

<div class="container">
        <table border=1 class="table">
          <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>Age</th>
            <th>Phone</th>
          </tr>
            <tr *ngFor="let d of data | async" [attr.id]="d.id"> <!--each row id == id-->
                <td>{{ d.id }}</td>
                <td>{{ d.name }}</td>
                <td>{{ d.email }}</td>
                <td>{{ d.age }}</td>
                <td>{{ d.phone }}</td>
                <button id="remove">DELETE ROW</button>
            </tr>
        </table> 
    </div>

Please let me know if more snippets are needed. Thank you.

like image 966
Wira Xie Avatar asked Jan 04 '23 06:01

Wira Xie


2 Answers

<div class="container">
        <table border=1 class="table">
          <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>Age</th>
            <th>Phone</th>
          </tr>
            <tr *ngFor="let d of data | async" [attr.id]="d.id"> <!--each row id == id-->
                <td>{{ d.id }}</td>
                <td>{{ d.name }}</td>
                <td>{{ d.email }}</td>
                <td>{{ d.age }}</td>
                <td>{{ d.phone }}</td>
                <button id="remove" (click)="deleteRow(d)">DELETE ROW</button>
            </tr>
        </table> 
    </div>

Typescript

deleteRow(d){
    const index = this.data.indexOf(d);
    this.data.splice(index, 1);
}
like image 84
Asakkour Soufiane Avatar answered Jan 18 '23 06:01

Asakkour Soufiane


you can add this code in you HTML file

<div class="container">
            <table border=1 class="table">
              <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Email</th>
                <th>Age</th>
                <th>Phone</th>
              </tr>
                <tr *ngFor="let d of data | async" [attr.id]="d.id"> <!--each row id == id-->
                    <td>{{ d.id }}</td>
                    <td>{{ d.name }}</td>
                    <td>{{ d.email }}</td>
                    <td>{{ d.age }}</td>
                    <td>{{ d.phone }}</td>
                    <button id="remove" (click)="deleteRow(d.id)">DELETE ROW</button>
                </tr>
            </table> 
        </div>

And add this code in youe component file

deleteRow(id){
        for(let i = 0; i < this.data.length; ++i){
            if (this.data[i].id === id) {
                this.data.splice(i,1);
            }
        }
    }
like image 39
AddWeb Solution Pvt Ltd Avatar answered Jan 18 '23 05:01

AddWeb Solution Pvt Ltd