Deleting items from list in angular

Viewed 70

I want to remove an item from the product list. In my code, it deletes the other items, not the specific one that i want to delete.. I already assigned which id to delete but it doesn't. I don't know why it deletes the others.. Please help. Thank you

Service

import { Injectable } from '@angular/core';
import { Product } from './Product';
import { PRODUCTLIST } from './ProductSupplier';

@Injectable({
providedIn: 'root'
})
export class ProductDatabaseService {
selectedProduct: Product | undefined;
productList:Product[]=[];

getProductList(): Product[] {
    return PRODUCTLIST;
}

deleteProduct(prodCode: number) {
    const product = PRODUCTLIST.splice(prodCode);
    return product;
}

addProductData(code: number, name: string, price: number, details: string) {
    let newProduct = new Product(code, name, price, details);
    PRODUCTLIST.push(newProduct);
}

getProductByID(prodCode: number) {
    const product = PRODUCTLIST.find(s => s.prodCode === prodCode);
    return product;
}


constructor() { }
}

I used the splice method to remove

Component class

import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Product } from '../Product';
import { ProductDatabaseService } from '../product-database.service';
import { Location } from '@angular/common';
import { Router } from '@angular/router';
@Component({
selector: 'app-product-details',
templateUrl: './product-details.component.html',
styleUrls: ['./product-details.component.css']
})

export class ProductDetailsComponent implements OnInit {
selectedProduct: Product | undefined;
productList: Product[] = [];
constructor(private productDBService: ProductDatabaseService,
private route: ActivatedRoute,
private location: Location,
private router: Router,
private router2: Router) { }

ngOnInit(): void {
    this.getProduct();
}

getProduct(): void {
    const prodCode = Number(this.route.snapshot.paramMap.get('prodCode'));
    this.selectedProduct = this.productDBService.getProductByID(prodCode);
}

updateProduct(prodCode: number) {
    this.router.navigate(['update-product', prodCode]);
}

deleteProduct(code: number) {
    this.productDBService.deleteProduct(code);
}

}

HTML Code

<div class="card" *ngIf="selectedProduct">
      <div class="card-header">
       <h2>{{selectedProduct.prodName | uppercase}} Details</h2>
      </div>
      <table class="table">
        <thead>
          <tr>
            <th scope="col">Product Code</th>
            <th scope="col">Product Name</th>
            <th scope="col">Product Price</th>
            <th scope="col">Product Details</th>
            <th scope="col">Actions</th>
            <th scope="col">Actions</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <th scope="row">{{selectedProduct.prodCode}}</th>
            <td>{{selectedProduct.prodName}}</td>
            <td>{{selectedProduct.prodPrice}}</td>
            <td>{{selectedProduct.prodDetails}}</td>
          <td><button (click)="updateProduct(selectedProduct.prodCode)" class ="btn btn-danger">Update</button></td>
          <td><button (click)="deleteProduct(selectedProduct.prodCode)" class ="btn btn-danger">Delete</button></td>
          </tr>
    
          </tbody>
          </table>
    
          <div class="vstack gap-2 col-md-4 mx-auto">
            <br>
            <button type="button" class="btn btn-secondary">Edit</button>
            <button type="button" class="btn btn-danger">Delete</button>
           
          </div>
          <div>
          <a  (click)="navigateBack()" class="btn btn-dark">Go Back</a>
          </div>

  
</div>

2 Answers

That's because you're using splice the wrong way. To remove with the splice method an item you would need to specify the amount of items you want to delete/add. In addition to that, the first argument of the splice method is the INDEX of the item to remove. So before calling the splice method. So you would do something like:

var array = [{prodCode: 20, name: "Product 1"}, {prodCode: 21, name: "Product 2"}, {prodCode: 22, name: "Product 3"}]
//we get the index of the item to remove
var indexToRemove = array.findIndex(product => product.prodCode == 21)
//we splice the array from the index of the item to remove of 1 item (the single item to remove)
array.splice(indexToRemove, 1);

here is a simple jsFiddle, just using the console to print the result:

https://jsfiddle.net/baduCleo/fhr3kzc4/

You should do 2 things:

  1. Find the index of the item that you want to remove
  2. Pass second parameter to splice() that specifies the number of items that should be removed. In this use case, second parameter should be 1, since you want to remove only one item.
const index = PRODUCTLIST.findIndex((product: any) => product.prodCode === prodCode);
if (index !== -1) PRODUCTLIST.splice(index, 1);
Related