Unable to utilize checkboxes for filtering in Angular 2 and beyond

I am working on a project that involves showcasing a list of participants. My goal is to set up a feature that allows filtering these participants based on different providers using checkboxes in real-time.

Below is a sample of the participants:

[
    { 'name': 'test1', 'provider' : {'name': 'provider1'}}
    { 'name': 'test2', 'provider' : {'name': 'provider2'}}
    { 'name': 'test3', 'provider' : {'name': 'provider3'}}
    { 'name': 'test4', 'provider' : {'name': 'provider1'}'}
 ..
]

In my HTML template, I have implemented the following checkboxes to display providers for filtering purposes:

These checkboxes can be used to filter the list of participants based on the selected providers.

<div class="form-group" *ngFor="let provider of providers">
    <input type="checkbox" name="providers" value="{{ provider.name }}" [(ngModel)]="provider.checked"
    (change)="displayParticipantsByProvider($event.target.value)">{{ provider.lastName }}
</div>

The actual display of the participants in the UI is handled as shown below:

<ul>
    <li *ngFor="let p of participants">{{ p.name }} - {{ p.provider.name }} </li>
</ul>

Here is the filter function utilized in the component:

displayParticipantsByProvider(filterVal: any) {
    if (filterVal === '0') {
      this.participants = this.cathechParticipants;
    } else {
      this.participants = this.participants.filter((item) => item.provider.includes(filterVal));
    }
}

The current implementation only allows for filtering based on a single checked item. My objective is to enhance this functionality to accommodate multiple checkboxes for filtering. How can I modify my code to achieve this, so that I can load participants based on multiple selected checkboxes?

Answer №1

Monitor selected items and compare them to the list of providers, then add them to the participants array.

This example demonstrates using Angular Material.

export class AppComponent {
  selectedProviders: any[];
  providers: any[];
  participants: any[];

  providerChange() {
    this.participants = [];
    for (const sp of this.selectedProviders) {
      for (const p of this.providers) {
        if (sp.provider.name === p.provider.name) {
          this.participants.push(p);
        }
      }
    }
  }

  ngOnInit() {
    this.providers = [
      { 'name': 'test1', 'provider': { 'name': 'provider1' } },
      { 'name': 'test2', 'provider': { 'name': 'provider2' } },
      { 'name': 'test3', 'provider': { 'name': 'provider3' } },
      { 'name': 'test4', 'provider': { 'name': 'provider1' } }
    ]
  }
}

HTML:

<mat-list-item class="primary-imenu-item" role="listitem">
    <mat-form-field class="select-form">
        <mat-select 
        placeholder="Providers" 
        name="providers" 
        class="filter-select" 
        [(ngModel)]="selectedProviders"
        (change)="providerChange()"
        multiple>
          <mat-option *ngFor="let p of providers" [value]="p">
            {{p.provider.name}}
          </mat-option>
        </mat-select>
    </mat-form-field>
  </mat-list-item>

  <ul>
    <li *ngFor="let p of participants">{{p.name}}</li>
  </ul>

Check out the live example on StackBlitz

Answer №2

Take a look at the provider list and identify those with the 'checked' property set to true using ngModel binding.

Answer №3

Custom HTML Code

<div class="form-group" *ngFor="let provider of providers;let i = index">
  <input type="checkbox" name="providers" value="{{ provider.name }}" [(ngModel)]="provider.checked"
  (change)="displayParticipantsByProvider()"><span class="font-weight-bold">{{ provider.name }}</span>
</div>
<ul>
  <li *ngFor="let p of participants">{{ p.name }} - {{ p.provider.name }} < /li>
</ul>

Custom TypeScript Code

participants = [];
 providers =  [
    { 'name': 'test1', 'provider' : {'name': 'provider1'}, checked: false},
    { 'name': 'test2', 'provider' : {'name': 'provider2'}, checked: false},
    { 'name': 'test3', 'provider' : {'name': 'provider3'}, checked: false},
    { 'name': 'test4', 'provider' : {'name': 'provider1'}, checked: false}
 ];
displayParticipantsByProvider() {
    this.participants = this.providers.filter((item, idx) => {
      if (item.checked) {

        return item;
      }
    });

  }

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

I'd like to know how to retrieve a total count of all the documents within a Firebase collection using Angular

My code currently fetches documents from a collection, but it's only bringing back 15 at a time (from what I can gather). This is causing an issue as I need to accurately determine the total number of documents in the collection for a program I'm ...

Navigate to the parent element in the DOM

Looking to add some unique styling to just one of the many Mat dialog components in my project. It seems like modifying the parent element based on the child is trickier than expected, with attempts to access the DOM through the <mat-dialog-container> ...

What is the best way to divide a string into an array containing both linked and non-linked elements?

I'm struggling to find the right solution to my problem. I need to create a view that is enclosed in a clickable div. The content will consist of plain text mixed with clickable URLs - the issue arises when clicking on a link also triggers the method ...

The parameter type 'never[]' cannot be assigned to the type 'T | (() => T)' in the argument

Is it possible for the useFetch hook to allow any type of array to be used as the data type? hooks/useFetch.ts: const useFetch = <T extends any[]>(dataUrl: string) => { const [data, setData] = useState<T>([]); const [error, setError] = ...

How can we effectively divide NGXS state into manageable sections while still allowing them to interact seamlessly with one another?

Background of the inquiry: I am in the process of developing a web assistant for the popular party game Mafia, and my objective is to store each individual game using NGXS. The GitLab repository for this project can be found here. The game includes the f ...

Why is it that after running "ng build" with Angular CLI, the project does not function properly?

(Greetings fellow Earthlings, I come in peace from the distant planet Angular2 (formerly known as Flex/Actionscript). Please pardon my ignorance with this question) Am I mistaken to assume that by running the "ng build" command on my project using Angular ...

Discover properties of a TypeScript class with an existing object

I am currently working on a project where I need to extract all the properties of a class from an object that is created as an instance of this class. My goal is to create a versatile admin page that can be used for any entity that is associated with it. ...

Using the hash(#) symbol in Vue 3 for routing

Even though I am using createWebHistory, my URL still contains a hash symbol like localhost/#/projects. Am I overlooking something in my code? How can I get rid of the # symbol? router const routes: Array<RouteRecordRaw> = [ { path: " ...

Module or its corresponding type declarations not found in the specified location.ts(2307)

After creating my own npm package at https://www.npmjs.com/package/leon-theme?activeTab=code, I proceeded to set up a basic create-react-app project at https://github.com/leongaban/test-project. In the src/index.tsx file of my react app, I attempted to im ...

Struggling to refine the result set using jsonpath-plus

Utilizing the jsonpath-plus module (typescript), I am currently working on navigating to a specific object within a json document. The target object is nested several levels deep, requiring passage through 2 levels of arrays. When using the following jsonp ...

Does the message "The reference 'gridOptions' denotes a private component member in Angular" signify that I may not be adhering to recommended coding standards?

Utilizing ag-grid as a framework for grid development is my current approach. I have gone through a straightforward tutorial and here is the code I have so far: typography.component.html https://i.stack.imgur.com/XKjfY.png typography.component.ts i ...

"An error occurred stating that _co.JSON is not defined in

During my attempt to convert an object into a string using the JSON method, I encountered an error upon loading my page: Error: _co.JSON is undefined The stacktrace for this error message is extensive and seems unnecessary to include at this point. Th ...

Exception Found: TypeError: is not a valid function

I'm trying to integrate a web service into my service file in order to use it with my typeahead Component, but I keep encountering an error message in my console. Here is the code for my service file: export class DslamService { private host = window ...

The marker is not updating in real-time with the actual latitude and longitude on the Google Maps angular

I have been attempting to update the marker in my Angular Google Map in real-time, but unfortunately it is not working as expected. It only displays the initial static data and then fails to update. Despite conducting a thorough search on Google, I have be ...

Upon initial page load, the distinctUntilChanged() function will not be triggered

Upon loading a page, I initiate the following method and utilize the returned list in a dropdown menu. The tap and switchMap functions are run as expected, however, the distinctUntilChanged function does not execute upon page load. Once the page is loade ...

Tips for populating the header of an angular-material card

I am working with an angular-material classic card that has the following template: <mat-card class="example-card"> <mat-card-header> <mat-card-title>Shiba Inu</mat-card-title> </mat-card-header> <mat-card-conten ...

Saving information obtained through Angular subscribe into a variable

One of the services I have is called getWeather, which contains a method that communicates with an API using longitude and latitude parameters and then returns the response: import { Injectable } from '@angular/core'; import { HttpClient } from ...

Matching TypeScript against the resulting type of a string literal template

My type declaration looks like this: type To_String<N extends number> = `${N}` I have created a Type that maps the resulting string number as follows: type Remap<Number> = Number extends '0' ? 'is zero' : Number ...

What exactly is a NativeScript app: is it the experience users have on their mobile devices, or the product they download from the app store?

Currently, I am diving into the world of Angular and exploring how to develop Angular applications with TypeScript while working on a C# ASP.Net Core Web Api project as the server side component. My question is this - if I create a NativeScript app in add ...

Routes within modules that are loaded lazily may not function properly for child components

I'm struggling to figure out the routing for a lazy loaded module. Take a look at this stackblitz I've created, which is based on the Angular lazy loading example with some modifications. Initially, the lazy loading function appears to be workin ...