How to remove an item from a list of displayed items in angular?

Photo by Rodolfo Clix on Pexels.com

Lets say you are displaying a list of items in a table using angular .

The template code might look like this:

<table class="table">


  <thead>

    <th>Name</th>
    <th>Company</th>

    <th>Expiry date</th>
  </thead>

  <tbody>

    <tr *ngFor="let product of products">
      <td hidden>{{product.id}}</td>
<td>{{product.name}}</td>
<td>{{product.company}}</td>
<td>{{product.expiryDate}}</td>
<td><button class="btn btn-primary" (click)="deleteProduct(product.id)">Delete</button></td>

    </tr>
  </tbody>
</table>

I am using bootstrap here and passing the id of the product that I want to delete when user clicks on delete button.

Here is the typescript code :

private products:any;

 deleteProduct(id){

    for(let i = 0; i < this.products.length; ++i){
      if (this.products[i].id === id) {
          this.products.splice(i,1);
      }
  }
  }

I have added only the code required to express the logic above. The logic to populate product items is left out for simplicity.

The method this.products.splice(index,noOfElements) does the job of removing the product item from the list.

Here

index denotes the position of the product item in the list ,

noOfElements denotes the number of elements to be deleted starting from the index.

I confused this with the method slice() for a while and took some time to realize the mistake.

Thats it! Splice it away!


Posted

in

by

Comments

Leave a Reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading