Filtering multiple columns in Angular Material's mat-table

I am attempting to integrate a filter into my table.

You can view the table with the filter in action on this live demo. However, I am facing an issue where the filters are not narrowing down the results as expected. For instance, when I apply the ID filter of 3 and status of active, it should only show 1 result since there is only 1 user with an ID of 3 and status of Active. Instead, it displays all users with an ID of 3 and also all users with an active status.

Are there any adjustments that can be made to the createFilter function to achieve the desired output?

// Custom filter method for Angular Material Datatable
createFilter() {
    let filterFunction = function (data: any, filter: string): boolean {
        let searchTerms = JSON.parse(filter);
        let isFilterSet = false;
        for (const col in searchTerms) {
            if (searchTerms[col].toString() !== '') {
                isFilterSet = true;
            } else {
                delete searchTerms[col];
            }
        }

        console.log(searchTerms);

        let nameSearch = () => {
            let found = false;
            if (isFilterSet) {
                for (const col in searchTerms) {
                    searchTerms[col].trim().toLowerCase().split(' ').forEach(word => {
                        if (data[col].toString().toLowerCase().indexOf(word) != -1 && isFilterSet) {
                            found = true;
                        }
                    });
                }
                return found;
            } else {
                return true;
            }
        };
        return nameSearch();
    };
    return filterFunction;
}

You can find the tutorial I followed along with the source code on this website.

Answer №1

When the searchTerms are matched, <code>found
will be set to true. If you only want to return true when all searchTerms are matched, you can achieve this with the following code:

if (isFilterSet) {
  for (const col in searchTerms) {
    if (searchTerms[col].toString() === '') {
      continue;
    } else {
      let found = false;
      searchTerms[col].trim().toLowerCase().split(' ').forEach(word => {
        if (data[col].toString().toLowerCase().indexOf(word) != -1 && isFilterSet) {
          found = true
        }
      });
      if (!found) {
        return false;
      }
    }
  }
  return true;
} else {
  return true;
}

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

Peer dependencies in NPM refer to dependencies that your project

I am currently in the process of upgrading from Angular 4 to Angular 5 and encountered some warnings along the way. Some of the warnings I received include: npm WARN @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88eb ...

VS Code is flagging TypeScript errors following the recent software update

After updating my VS Code, I started seeing TypeScript error messages like the following: ButtonUnstyled.types.d.ts: Module '"/components/node_modules/@types/react/index"' can only be default-imported using the 'esModuleInterop&a ...

Having trouble with the SELECT functionality in Angular2/4 and SAFARI?

Having a major issue with the basic html SELECT component on SAFARI. Here is the code snippet: Initial Declaration idFamily:any = null; listProductFamily: ProductFamily[]; Loading listProductFamily this.productFamilyService.GetAll().subscribe( ...

Issue encountered when assigning a CSS class to Angular component

My module contains a table structure with specific components. Here is the source code for table.component.html: <table border=1> <theader></theader> </table> The source code for theheader.component.html is as follows: <thea ...

The type does not contain a property named 'x' - Error in Promise syntax - TS2339

I encountered a problem while working with Typescript that I couldn't quite figure out. Although I came across similar issues in other topics, I'm still struggling to find a solution for my particular issue. I can easily log userCredential.user.m ...

Disabling eslint does not prevent errors from occurring for the unicorn/filename-case rule

I have a file called payment-shipping.tsx and eslint is throwing an error Filename is not in camel case. Rename it to 'paymentShipping.tsx' unicorn/filename-case However, the file needs to be in kebab case since it's a next.js page that s ...

Avoid connecting redux to a component in TypeScript and React

I am having an issue with the "connect" function not wrapping my App component, causing Redux to not work. I have tried cloning some repositories with react+redux+typescript and they all work fine, but my application does not. As a result, I am unable to ...

Troubleshooting problems with Angular 6 update through the command "ng update"

https://i.stack.imgur.com/LuPSs.png I am currently in the process of upgrading from Angular version 5 to 6. When using the "ng update" command, I encountered a problem that is shown in the attached screenshot. Can someone guide me on how to resolve this ...

Angular 7 and Webpack 4 combine to create a secure environment for CSS encapsulation

I find myself in a challenging situation where I have a hybrid environment consisting of both Angular 1.x and Angular 7 routes. The Angular 1.x routes rely on the older version of Bootstrap (3), while the Angular 7 routes are supposed to utilize Bootstrap ...

Encountering an issue while adding types to a custom component in a Formik form: Error message states that type 'T[keyof T]' cannot be assigned to type 'string'

I'm delving into TypeScript for the first time and attempting to incorporate it into a previous project as a learning exercise. I've hit a roadblock while trying to add types to a custom form field component in Formik, encountering an error mess ...

A guide on dynamically displaying a component within another component using Angular2

I am currently facing a challenge where I need to dynamically display a component within another component. When a particular record is clicked, I want to replace that record with the selected component and perform specific actions on it. Does anyone have ...

Step-by-step guide to setting up Next.js with TailwindCSS using JavaScript explicitly

Currently, I am working on a Next.js project where all the files have the extension .tsx (TypeScript). Although TypeScript is similar to Java, I prefer to have the file ending as .js. I attempted to modify the command (npx create-next-app -e with-tailwin ...

Utilizing Dependency Injection with Angular 2, Ionic 2, and TypeScript

I'm currently facing issues with bootstrapping certain files in my application. Specifically, I am working on extending the Ionic2 tabs example. Within my codebase, I have a Service and a User file, both annotated with @injectable. I am aiming for a ...

A method for transferring information stored in chrome.storage to a variable within an Angular component

How can I effectively assign data fetched from chrome.storage.sync.get to my Angular component's variable? Below is the code snippet of my component: export class KTableComponent implements OnInit { words: string[] = []; constructor() { } ...

Customizing Angular with SASS Theming

After coming across the query How can switchable themes be implemented in SCSS?, particularly the second response which drew inspiration from this insightful Medium post, I decided to try implementing themes using SASS on my project. Unfortunately, I hav ...

Ways to verify the functionality of a function utilizing a Subscription that yields no return value

I'm working with a TypeScript ModelService that has an edit function: edit(model: Model): Observable<Model> { const body = JSON.stringify(model); return this.http.put(`/models/edit/${model.id}`, body)); } Additionally, there is a TypeScrip ...

Adding .js extension to relative imports in TypeScript compilation for ES6 modules

This particular issue may appear simple at first glance, but determining the required settings/configurations to resolve it is not straightforward. Below are the directory structure and source code for a Hello World program: Directory Structure: | -- Hel ...

Setting up a Typescript project with a shared package configuration

Before I begin, there are a few premises to consider: I require a shared package that will be included in three other packages, TypeScript, Only one node modules, Ability for multiplatform usage (Windows / Linux), To utilize dependencies from the shared ...

Edge fails to access Webservice from file:/// host

When attempting to access a webservice that I've created in C# using Typescript and the fetch-api, everything works smoothly in Chrome and Firefox. However, in Edge, the access fails. I've tried both POST and GET methods in Edge, but neither are ...

The main module's postinstall process is initiated before the sub-module's postinstall process

Update: I am seeking guidance on how to install a module from GitHub instead of npm. That's the main query. In case you're wondering why: I'm currently working on some confidential projects and prefer not to publish the code. As a result, ...