Home > Net >  Items are not filtered when the checkbox is unchecked
Items are not filtered when the checkbox is unchecked

Time:12-28

I have an array of four categories. I would like to put each individual category on a separate checkbox so that when clicked the array is filtered by a specific category. With the help of the code below, I want to do the following: if the array of checkboxes already has one of the categories, it will not be added the second time by clicking. Unfortunately, I don't have the filtering to remove the category when the checkbox is unchecked. Please tell me what is wrong with? And please tell me, can this logic be written better? Thank you very much

public allProductsCategories: string[] = ["сars", "clothes", "home", "sport"];
public checkedCategoriesFilter: string[] = [];

public filterProductsCategoryCheckboxClick(event: Event): void {
   const isCheckboxChecked = (<HTMLInputElement>event.target).checked;
   const checkboxDataValue = (<HTMLInputElement>event.target).value;

   if (isCheckboxChecked) {
     if (!this.checkedCategoriesFilter.includes(checkboxDataValue)) {
       this.checkedCategoriesFilter.push(checkboxDataValue)
     } else {
       return;
     }
   } else {
     console.log('unchecked')
     this.checkedCategoriesFilter.filter(category => category === checkboxDataValue);
}
   console.log(this.checkedCategoriesFilter);
}

html

<div *ngFor="let checkboxCategory of allProductsCategories">
    <input
      type="checkbox"
      [value]="checkboxCategory"
      (change)="filterProductsCategoryCheckboxClick($event)"
    >
</div>

CodePudding user response:

Filter method return an array and need to store it in array.

Update your component.ts file code as given below:

 public allProductsCategories: string[] = ['сars', 'clothes', 'home', 'sport'];
 public checkedCategoriesFilter: any = [];

 public filterProductsCategoryCheckboxClick(event: Event): void {
    const isCheckboxChecked = (<HTMLInputElement>event.target).checked;
    const checkboxDataValue = (<HTMLInputElement>event.target).value;

    if (isCheckboxChecked) {
      if (!this.checkedCategoriesFilter.includes(checkboxDataValue)) {
        this.checkedCategoriesFilter.push(checkboxDataValue);
      } else {
        return;
      }
    } else {
      console.log('unchecked');
      this.checkedCategoriesFilter = this.checkedCategoriesFilter.filter(
        (category) => {
          return category !== checkboxDataValue;
        }
      );
     }
    console.log(this.checkedCategoriesFilter);
  }
  • Related