Search code examples
angulardelete-row

How do I delete an item(id) from an array using click?


I iam using angular 8 and i'm beginner so i need a help I want to delete an item from array using (click)="deleteEmployee(el.id)" im trying to use splice but i have an error their :

this is Component.ts code :

  employee: Employe;
  id: number;

  _employesArray:Employe[]=[];
  headElements = ['ID', 'Nom', 'Prenom', 'Email', 'Telephone', 'CompteStatut'];



  constructor(private route: ActivatedRoute, private http:HttpClient, private employeservice:EmployeService, private router: Router) {

   }

  ngOnInit() {
    this.employee = new Employe();

    this.id =this.route.snapshot.params['id'];


    this.employeservice.getEmployee(this.id)
      .subscribe(data => {
        console.log(data)
        this.employee = data;
      }, error => console.log(error));
    this.reloadData();
  }

  reloadData() {
    this.employeservice.getEmp().subscribe(
      data=>{
        this._employesArray=data;


      },
      err=>{
        console.log("An error has occured")
      }
    );

  }

  deleteEmployee(id: any) {
    this.employeservice.deleteEmployee(this.id)
      .subscribe(data =>{
      this._employesArray.splice(this._employesArray.indexOf(this.id), 1);
      this.reloadData();
      },

       error => console.log(error));

  }

Solution

  • Few this to clear out here. I see you forwarding the ID to a API call here. Why not show the returned result of the API call straight away in the Angular app by removing the object from the API or DB straight away?

    If you want to remove a specific object in a your arrray you need to iterate it over.

    Try the below snippet:

    this._employesArray= this._employesArray.filter(employee=> employee.id === this.id);