Angular 6 Checkbox Selector - Filtering Made Easy

How can I filter a list of JSON objects (Products) by the 'category' variable using checkboxes?

An example product object is shown below:

  {
  'bikeId': 6,
  'bikeName': 'Kids blue bike',
  'bikeCode': 'KB-3075',
  'releaseDate': 'June 28, 2016',
  'description': 'Kids blue bike with stabilizers',
  'category': 'kids',
  'price': 290.00,
  'starRating': 4.8,
  'imageUrl': 'https://openclipart.org/image/2400px/svg_to_png/1772/bike-kid.png'
}

The current ngFor Loop code is as follows:

   <tr *ngFor="let product of products">
                       <td><img *ngIf='showImage' 
                         [src]='product.imageUrl' 
                        [title]='product.bikeName'
                        [style.width.px]='imageWidth'></td>
                       <td>{{product.bikeName}}</td>
                       <td>{{product.bikeCode}}</td>
                       <td>{{product.releaseDate}}</td>
                           <td>{{product.price}}</td>
                           <td>{{product.starRating}}</td>
</tr>

And the current Checkboxes are as follows:

 <input type="checkbox" name="All" value="true" /> Mens 
                <input type="checkbox" name="All" value="true" /> Womens 
                <input type="checkbox" name="All" value="true" /> Kids 

I'm posting this question after searching forums all day with no luck. Many answers I found were either outdated or not working when I tested the code. Any assistance would be greatly appreciated.

Answer №1

It's surprising that you struggled to find an example online, considering the numerous ways to tackle this issue. My approach is just one method among many.

In my solution, I maintain the original product source untouched but create a secondary array to store the displayed products. Each checkbox is linked to a property of a filter model, and when there's a change, I trigger filterChange() to update the filtered products based on that model.

You can skip using NgModel and dual binding by dynamically generating filters from an array, which is beneficial for scalability as your application expands. Additionally, you could leverage Observables or implement a Pipe to filter the array within NgFor loop. The options are limitless.

MyComponent.ts

export class MyComponent {
  filter = { mens: true, womens: true, kids: true };
  products: Product[] = []
  filteredProducts = Product[] = [];

  filterChange() {
    this.filteredProducts = this.products.filter(x => 
       (x.category === 'kids' && this.filter.kids)
       || (x.category === 'mens' && this.filter.mens)
       || (x.category === 'womens' && this.filter.womens)
    );
  }
}

MyComponent.html

<tr *ngFor="let product of filteredProducts"> <!-- ... --> </tr>
<!-- ... --->
<input type="checkbox" [(ngModel)]="filter.mens" (ngModelChange)="filterChange()" /> Mens 
<input type="checkbox" [(ngModel)]="filter.womens" (ngModelChange)="filterChange()" /> Womens 
<input type="checkbox" [(ngModel)]="filter.kids" (ngModelChange)="filterChange()" /> Kids

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing the ERROR TypeError in an Angular form where "_co.service.formData" is undefined?

My attempt to create a form in Angular 7 has resulted in an error message: ERROR TypeError: "_co.service.formData is undefined" Here is the HTML code for the component: <form (sumbit)="signUp(form)" autocomplete="off" #form="ngForm"> <div clas ...

What is the best way to eliminate duplicate data from an HTTP response before presenting it on the client side?

Seeking assistance on how to filter out duplicate data. Currently receiving the following response: {username:'patrick',userid:'3636363',position:'employee'} {username:'patrick',userid:'3636363',position:&a ...

Tips for sorting through the state hook array and managing the addition and removal of data within it

Having trouble finding a solution for filtering an array using the React useState hook? Let me assist you. I have declared a string array in useState- const [filterBrand, setFilterBrand] = useState<string[]>([]); Below is my function to filter this ...

Accessing properties for objects with map-like characteristics

Many interfaces allow for arbitrary data, as shown below: interface Something { name: string; data: { [key: string]: any }; } The problem arises when trying to access or set values on objects with arbitrary keys in Typescript. let a: Something = { ...

Converting an Observable variable to a specific type in Typescript

I am currently utilizing Angular 12. To avoid duplicating the same service logic, I am experimenting with creating a base class that includes all HTTP methods and then extending a child class to utilize in the components. crud.service.ts @Injectable({ ...

Using JavaScript to ensure that a div is not hidden on page load if a checkbox is unchecked

Upon inspecting a page, I am implementing a script to check if a checkbox is selected. If not selected, the goal is to hide a specific div element. While troubleshooting this issue, I suspect the problem may be due to the lack of an inline element within t ...

Changing the name of an Angular2 import module

Deciding to improve readability, I opted to rename the @angular module to angular2 and gain a better understanding of how imports function. Prior to making this change, the systemjs.config.js appeared like so: (function(global) { var map = { ...

Is there a way to incorporate several select choices using specific HTML?

I am currently trying to dynamically populate a select tag with multiple option tags based on custom HTML content. While I understand how to insert dynamic content with ng-content, my challenge lies in separating the dynamic content and wrapping it in mat ...

Option to modify the arguments of a method in a parent class

I encountered an interesting problem recently. I have two classes: class Animal { public talk() { console.log('...'); } } and class Dog extends Animal { public talk(noise: string) { console.log(noise); super.talk() } } The i ...

Creating React components with TypeScript: Defining components such as Foo and Foo.Bar

I have a react component defined in TypeScript and I would like to export it as an object so that I can add a new component to it. interface IFooProps { title:string } interface IBarProps { content:string } const Foo:React.FC<IFooProps> = ({ ...

What is the best approach in Typescript to ensure type understanding when importing using require()?

Currently, I am working with TypeScript within IntelliJ. Let's say I have the following code: const functions = require('firebase-functions'); Then I proceed to use it in this manner: exports.doSomething = functions.https.onCall((data, c ...

Angular: Safely preserving lengthy content without the use of a database

As a beginner working on an Angular 11 educational website with approximately 20 static articles, I created a component template for the articles to receive text inputs. However, I am wondering if there is a more efficient way to handle this. Is there a ...

The constant issue persists as the test continues to fail despite the component being unmounted from the

import { render, screen } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import { act } from 'react' import Notifications, { defaultNotificationTime, defaultOpacity, queuedNotificationTime, fa ...

Is there a way to automatically update the button text based on the route name without requiring user interaction?

I need to dynamically change the text on a button in my header based on the current route. When on the login page, the button should say "Signup" and when on the signup page, it should say "Login". I want this text change to happen without having to click ...

Implementing Routes in Express Using Typescript Classes

Seeking assistance in converting a Node.js project that utilizes Express.js. The objective is to achieve something similar to the setup in the App.ts file. In pure Javascript, the solution remains unchanged, except that instead of a class, it involves a mo ...

"Embrace the powerful combination of WinJS, Angular, and TypeScript for

Currently, I am attempting to integrate winjs with Angular and TypeScript. The Angular-Winjs wrapper functions well, except when additional JavaScript is required for the Dom-Elements. In my scenario, I am trying to implement the split-view item. Although ...

A TypeScript utility type that conditionally assigns props based on the values of other properties within the type

There is a common need to define a type object where a property key is only accepted under certain conditions. For instance, consider the scenario where a type Button object needs the following properties: type Button = { size: 'small' | &apo ...

What methods are available to prevent redundant types in Typescript?

Consider an enum scenario: enum AlertAction { RESET = "RESET", RESEND = "RESEND", EXPIRE = "EXPIRE", } We aim to generate various actions, illustrated below: type Action<T> = { type: T; payload: string; }; ty ...

What is the reason behind Typescript's discomfort with utilizing a basic object as an interface containing exclusively optional properties?

Trying to create a mock for uirouter's StateService has been a bit challenging for me. This is what I have attempted: beforeEach(() => { stateService = jasmine.createSpyObj('StateService', ['go']) as StateService; } ... it(& ...

I'm encountering issues with undefined parameters in my component while using generateStaticParams in Next.js 13. What is the correct way to pass them

Hey there, I'm currently utilizing the App router from nextjs 13 along with typescript. My aim is to create dynamic pages and generate their paths using generateStaticParams(). While the generateStaticParams() function appears to be functioning corre ...