Home > Software design >  After filtering the array, the elements disappear
After filtering the array, the elements disappear

Time:12-20

I need your help. I have an array of items and each item has a category field that I want to filter the array by. I also have a separate array of categories that I will use to select the category to filter on. Unfortunately, it filters the elements only once, when I select a different category, all the elements disappear - I need to reload the page. What is my problem? Thank you very much

html

<form [formGroup]="form">
   <select formControlName="category" (change)="filterProductsCategory()">
     <option *ngFor="let category of allProductsCategories" [value]="category"> {{category}} </option>
   </select>
</form>

<div *ngFor="let product of allProductList" >
   <div>
     {{product.title}}
   </div>
</div>

typescript

export class AllProductsComponent implements OnInit {

public form: FormGroup;
public allProductsCategories: string[] = ["electronics", "jewelery", "men's clothing", "women's clothing"];
public allProductList: IProduct_model[];

 ngOnInit(): void {
   this.form = new FormGroup({
     category: new FormControl(null)
   })

   this.productService.getAllProducts().subscribe(value => {
     this.allProductList = value;
   })
}

public filterProductsCategory(): void {
   const categoryOptionValue = this.form.controls['category'].value;
   this.allProductList = this.allProductList.filter(el => el.category === categoryOptionValue);
}

CodePudding user response:

You are overriding your list when filtering. Therefore you are losing all elements in your list which do not met your filter. When you filter the second time you filter the alredy filtered list which does not make any sense.

Take a second list like this:

<form [formGroup]="form">
   <select formControlName="category" (change)="filterProductsCategory()">
     <option *ngFor="let category of allProductsCategories" [value]="category"> {{category}} </option>
   </select>
</form>

<div *ngFor="let product of filteredProductList" >
   <div>
     {{product.title}}
   </div>
</div>

And in your typescript:

export class AllProductsComponent implements OnInit {

public form: FormGroup;
public allProductsCategories: string[] = ["electronics", "jewelery", "men's clothing", "women's clothing"];
public allProductList: IProduct_model[];
public filteredProductList: IProduct_model[];

 ngOnInit(): void {
   this.form = new FormGroup({
     category: new FormControl(null)
   })

   this.productService.getAllProducts().subscribe(value => {
     this.allProductList = this.filteredProductList = value;
   })
}

public filterProductsCategory(): void {
   const categoryOptionValue = this.form.controls['category'].value;
   this.filteredProductList = this.allProductList.filter(el => el.category === categoryOptionValue);
}
  • Related