Kindth
Kindth

Reputation: 337

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));

  }

Upvotes: 0

Views: 750

Answers (2)

Dilani Alwis
Dilani Alwis

Reputation: 749

You can simply use the .filter builtin method to remove an item from an array.

 deleteEmployee(id: any) {
    this.employeservice.deleteEmployee(id)
      .subscribe(
        data => {
          // this will return a new array of employees after removing the employee given by the id
          this._employesArray = this._employeeArray.filter(employee => employee.id !== id);
        },
        error => console.log(error));
  }

Upvotes: 2

SELA
SELA

Reputation: 6868

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);

Upvotes: 2

Related Questions