Shirish Pokhrel
Shirish Pokhrel

Reputation: 245

Edit and Delete table data in angular

I am learning Forms in Angular. I made a form and on Submit the form data is shown in a table below. I want to add a delete and edit functionality to that. Kindly guide me.

Below is the stackblitz of the project:

https://stackblitz.com/edit/angular-forms-tdf

Upvotes: 2

Views: 8887

Answers (3)

Storytellerr
Storytellerr

Reputation: 805

if you want multiple item to delete you have to add one more property to user which is selected as a type boolean, then with the help of checkbox take input and delete value.

<tbody >
     <tr *ngFor="let user of formData">
      <td *ngIf="editMode"> <input type="checkbox" [(ngModel)]="user.selected"/></td>
      <td>{{user.Name}}</td>
      <td>{{user.email}}</td>
      <td>{{user.phoneNumber}}</td>
      <td>{{user.password}}</td>
      <td>{{user.gender}}</td>
     </tr>
</tbody>

then on delete button delete all selected item

delete(){
  this.formData =  this.formData.filter( value =>{
    return value.selected === false;
    })
  }

and send updated data to backend on save button. I have updated the Stackblitz.

Upvotes: 2

Bala
Bala

Reputation: 11

i would not prefer removing any element by using filter until that's the only way because it has complexity of O(n) (means it will loop all over the elements to find which element to delete) i would prefer removing any element by index which has complexity O(1).

delete(index): void{
    // delete directly via index by javascript splice() method
    });

Upvotes: 1

KeenLearnerA
KeenLearnerA

Reputation: 159

Assuming you have are storing the data you want to remove in a database, you will need to create your buttons reflecting edit and delete, create method for each in your html file , for example

<div class="col-md-2"><button class="btn btn-danger" (click)="delete(std)">DELETE</button></div>

and in your ts file you would insert code such as

//you make a call to your APi which references your backend
delete(person: Persons): void{
    this.apiService.deletePerson(person.Id)//method name in your services.ts file
    .subscribe(data =>{
      this.person = this.person.filter(u => u !==person);
    });

as mentioned above, you will also need a call in your services file(please note this example is using php and mysql), such as:

deletePerson(Id: number):Observable<ApiResponse>  {
    return this.http.delete<ApiResponse>(`http://localhost/angular9crud/delete.php?id=${id}`);
  }

If you are using backend, such as php then I recommend watching few youtube videos as there is plenty of information and detailed explanations available

Upvotes: 4

Related Questions