Home > Enterprise >  How to remove the selected data from saved data when we click on button in a selected one
How to remove the selected data from saved data when we click on button in a selected one

Time:04-27

In my application I have saved the data when we click on it(we can add the multiple data by entering some data and save the multiple data by clicking the save button).

.component.html

<button
        
        (click)="saveDetails()">
        SAVE HABITS
      </button>

<span   
          [popoverOnHover]="false"
          type="button"
          [popover]="customPopovers"><i  ></i> Delete</span>
      
        <div >
    <popover-content #customPopovers [closeOnClickOutside]="true">
          <h4>Do you want to delete this habit?</h4>
          <button
           deletedata()>   yes </button>
       <button
        >  No </button>
       
        </popover-content></div>

In the above code when we clcik on delete button it will show some popup having buttons yes and no so my requirement is when we clcik on yes button in from the popover it has to delete the particular one.

.component.ts

 public saveDetails() {
   if (this.selectedCategoryDetails) {
      this.selectedCategoryDetails.forEach((selectedCategory) => {
        if (selectedCategory.category === categoryDetails.category) {
          isCategoryExist = true;
          selectedCategory.habitDetails = selectedCategory.habitDetails.concat(
            categoryDetails.habitDetails
          );
        }
      });
    }
    if (!this.selectedCategoryDetails || !isCategoryExist) {
      this.selectedCategoryDetails.push(categoryDetails);
    }

    this.clinicalNoteForm.patchValue({
      category: null,
    });
    this.healthyHabits.clear();
  }

The above code I have written is for saving the data(we can enter multiple data and save multiple )

Like the above I have to delete the particular one when we click on yes button from the popover.

Can anyone help me on the same

CodePudding user response:

If you're iterating in your html like:

<... *ngFor="let categoryDetails of selectedCategoryDetails" ...>

and your button with deletedata() is in the scope of ngFor, you can:

  1. Change your iteration to include index of an item and trackBy function for updating the array in view:

<... *ngFor="let categoryDetails of selectedCategoryDetails; let i = index; trackBy: trackByFn" ...>

  1. On the button click pass the index to deletedata() method like:

deletedata(index)

  1. Create your deletedata method like:

    deletedata(index:number){
        this.selectedCategoryDetails.splice(index, 1);
        // other code here, like calling api
        // to update the selectedCategoryDetails source
        // etc.
    }
    
  2. Create trackByFn method like:

     trackByFn(index,item){
         return index;
     }
    
  • Related