Utilizing Checkboxes for Filtering Mat-Table Data in Angular 8

I've been attempting to implement checkbox filtering for a table, but none of my attempts have been successful so far.

Here is a snippet of my table structure:

 <mat-table [dataSource]="dataSource"  [hidden]="!show" matSort >
    <!-- Location  -->
    <ng-container matColumnDef="AITOR">
      <mat-header-cell *matHeaderCellDef> Location </mat-header-cell>
      <mat-cell *matCellDef="let container"> {{container.AITOR}} </mat-cell>
    </ng-container>
        <!-- Type  -->
        <ng-container matColumnDef="SOG_MCOLH">
          <mat-header-cell *matHeaderCellDef mat-sort-header > Container Type </mat-header-cell>
          <mat-cell *matCellDef="let container"> {{container.SOG_MCOLH}} </mat-cell>
        </ng-container>

This is how my checkbox setup looks like:

<input  class="CheckBoxClass" type="checkbox" value="RG" (onclick)="doFilter(RG)" >
<mdb-icon class="IconClass" fas icon="tint"></mdb-icon>
RG<br>

This is the function I am using in my component:

public doFilter = (value: string) => {
  this.dataSource.filter = value.trim().toLocaleLowerCase();
}

I've experimented with using [checked] instead of (onclick), but neither seem to be effective. I also tried implementing a Pipe, however, I found it confusing and struggled to write it properly. Despite searching online for a solution, I haven't come across any examples of a checkbox filter implementation.

Answer №1

I was able to figure out the solution for this issue -

If you want to utilize checkboxes for filtering, you must create a custom filterPredicate.

Below is my updated code snippet featuring the new filterPredicate and HTML:

HTML :

<div class="CheckBoxStyle">
<mat-checkbox  class="CheckBoxClass" value="RG" (change)="addFilter($event)">RG</mat-checkbox>
<mdb-icon class="IconClass" fas icon="tint"></mdb-icon>
</div>

Component - filterPredicate along with the method that observes it and puts it into action :

ngOnInit() {
  this.marinService.getAllContainers().subscribe((result)=>{
    this.dataSource = new MatTableDataSource(result);
    this.total = this.dataSource.length;

    this.dataSource.filterPredicate = (data: Container, filter: any) => {
      return filter.split(',').every((item: any) => data.SOG_MCOLH.indexOf(item) !== -1);
    };
    this.filterCheckboxes.subscribe((newFilterValue: any[]) => {
      this.dataSource.filter = newFilterValue.join(',');
        });
    )}        
  }

addFilter(change: MatCheckboxChange) {
  if (this.filterCheckboxes.value.some((a: any) => a === change.source.value)) {
    this.filterCheckboxes.next(this.filterCheckboxes.value.filter((a: any) => a !== change.source.value));
  } else {
    this.filterCheckboxes.next(this.filterCheckboxes.value.concat(change.source.value));
  }
}

This method worked for me in utilizing checkboxes to filter a datatable. Hopefully, it can help you as well.

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

Conceal object from inventory upon clicking

As someone who is new to React and Typescript, I am facing challenges in understanding how to hide a ticket from the list when the hide button is clicked. displayTickets = (tickets: Ticket[]) => { const filteredTickets = tickets.filter(t => ...

Utilizing Angular resolver to inject the router functionality

In my Angular (v13) application, I have defined a resolver to interact with a Wordpress backend. The purpose of this resolver is to determine the post type and ID from Wordpress when a user accesses a URL, and then route accordingly (to a post list, single ...

What causes the dispatch property to be undefined in a connected wrapped component within a connected Higher Order Component while using react-redux in conjunction with typescript?

As a new user, I am facing a particular challenge. I am working with a Higher Order Component (HoC) that injects properties into a wrapped component. The HoC itself returns a React.ComponentClass that is connected to the redux store with mapped and dispatc ...

Error in Typescript: Property 'timeLog' is not recognized on type 'Console'

ERROR in src/app/utils/indicator-drawer.utils.ts:119:25 - error TS2339: Property 'timeLog' does not exist on type 'Console'. 119 console.timeLog("drawing") I am currently working with Typescript and Angular. I have ...

Angular 4: Issue with sending POST data via HTTP requests

I am currently working on developing a Web Application and I am facing an issue with testing the HTTP functions. Here is an example of my code snippet: import { Injectable } from '@angular/core'; import { Headers, RequestOptions, Http } from & ...

Tips on retrieving a strongly typed value from a method using Map<string, object>

Having had experience working with C# for a while, I recently ventured into a Node.js project using TypeScript V3.1.6. It was exciting to discover that TypeScript now supports generics, something I thought I would miss from my C# days. In my C# code, I ha ...

Tips for ensuring a method is not invoked more than once with identical arguments

I'm grappling with a challenge in JavaScript (or typescript) - ensuring that developers cannot call a method multiple times with the same argument. For instance: const foo = (name: string) => {} foo("ABC") // ok foo ("123") ...

Tips on sending various properties to makeStyles() using TypeScript

After learning how to pass 1 prop to makeStyle() from a resource, I decided to try passing in 2 props for my project. However, I encountered an error stating cannot find name 'props'. Any assistance on this issue would be greatly appreciated! con ...

Angular 11 now includes the ability to implement lazy loading for modules

Here is the configuration of my app-routing.module.ts: const routes: Routes = [ { path: 'login', component: LoginComponent }, { path: '', canActivate: [AuthGuard], component: HomeComponent, children ...

Determine the data type of a variable in TypeScript by utilizing the compiler API

I am facing an issue with retrieving the type of a variable using the compiler API. Here is some background information on my situation: Since I execute everything in memory, I have had to create my own compiler host. This is necessary because the typechec ...

Ways to integrate npm dependencies into your Cordova plugin

Currently working on implementing a Cordova plugin called core-cordova found in this repository. This particular plugin has a dependency on another NPM package. The issue arises after installing the plugin in my app using: $ cordova plugin add @aerogears ...

Translation of menu item label has not been executed

Here we have a component called SidebarMenuComponent that is not translating the labels of its menu items correctly. The goal is to get the labels translated, but the current implementation is failing. What is the correct approach to apply translation in t ...

The code is looking for an assignment or function call, but found an expression instead: no-unused-expressions

Why am I encountering an ESLint error when using Ternary with 2 statements here? ESLint Error: no-unused-expressions res?.isSuccessful ? (this.toastService.showToast(res.message, 'success'), this.queueDataService.addMember(attendee)) : ...

The Tools of the Trade: TypeScript Tooling

Trying out the amazing Breeze Typescript Entity Generator tool but encountering an error consistently. Error: Experiencing difficulty in locating the default implementation of the 'modelLibrary' interface. Options include 'ko', 'b ...

The request to DELETE the employee on the server at http://localhost:3000/employees/$%7Bid%7D could not be processed because it was not found

removeEmployee(id: number): Observable<any> { return this._http.delete('http://localhost:3000/staff/${id}'); } } error:HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: 'Not Found', url: 'http://localhost:30 ...

Different Options to Explore Instead of Using @apollo/federation Library

We are currently developing typescript microservices with REST APIs and are exploring the possibility of integrating GraphQL into each microservice, along with implementing an API Gateway at the top level to combine everything into a single API. Although ...

What could cause a member variable to be uninitialized in the ngInit method in Ionic/Angular, even though it was initially set in the constructor

Despite setting the modal form to be bound to an instance of "Foo" during its construction, I encountered a strange issue where, post-constructor, this.foo became undefined. Even after verifying this through breakpoints and console.log, the problem persist ...

Converting numbers to strings based on locale in React Native

I have a quantity that, when using the amount.toFixed() function, produces the string "100.00". I would like this result to be formatted according to the specific locale. For example, in Italian the desired output is 100,00, while in English it should be ...

The specified argument, 'void', cannot be assigned to a parameter that expects 'SetStateAction | undefined'

Currently, I am engaged in a TypeScript project where I am fetching data from an endpoint. The issue arises when I attempt to assign the retrieved data to my state variable nft using the useState hook's setNft function. An error is being thrown specif ...

Expanding the visual in a spacious display with the help of ng-carousel from the Bootstrap framework

I have created a slider with multiple images on a website using Angular 4. The slider is displayed in a small area of the webpage and I would like to add a feature where the user can click on an image to view it in a larger screen or window. This could i ...