user1532669
user1532669

Reputation: 2378

Angular: Filter product based on category

I am trying to filter products that have the category "Beds". I have two products in my products.json file, one with the category "Beds" and the other has the category "Wardrobe". However both products are output to the page when only the filtered product should be displayed.

The below function should filter the products by first running the regex which strips out everything after "Beds" in the first element of the breadcrumb array and then compare it to this.listFilter which is set to "Beds". The regex appears to work as expected, so I think the problem is elsewhere.

       "categories": {
          "category": {
             "category_name": "Double Bed Frame",
             "breadcrumb": [
                "Beds > Bed Frames > 4ft6 Double Bed Frames",
                "Beds > Bed Frames > Metal Bed Frames > 4ft6 Double Metal Bed Frames"
             ]
          }
       },

Function to filter products:

  performFilter(): IProduct[] {
    return this.products.filter((product: IProduct) => product.categories.category.breadcrumb[0].replace(/^([a-z]+)\s+>.*?$/i, '$1').indexOf(this.listFilter) !== -1);
  }

The relevant code is in the subcategory component at the stackblitz link below:

https://stackblitz.com/edit/angular-htpmwq

Navigating to the link below currently shows two products with different categories, only one should show.

https://angular-htpmwq.stackblitz.io/beds

Upvotes: 0

Views: 1573

Answers (1)

Frank Adrian
Frank Adrian

Reputation: 1234

2 Things:

.replace() returns a string, so you can just compare it with ===

And initally you never called preformFilter, so i added the call to the subscription of your getProducts call.

https://stackblitz.com/edit/angular-7tynwf?file=src/app/subcategory/subcategory.component.ts

Upvotes: 1

Related Questions