2

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

1
  • First you'll need to add a id of some sort to the formData entries, so that you can tell them apart. Then you simply edit/delete the data from that array. Also, type your variables - it's Typescript, Commented Aug 6, 2020 at 7:20

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.