The Angular filter feature operates on individual columns instead of filtering all columns simultaneously

Introduction

I am currently working on implementing a feature in my Angular application where the column filter continuously updates the results based on the selected filters. The issue I'm facing is that when I select a filter in one column, it correctly filters the data but as soon as I select a different column filter, it adds back all the previously filtered items along with the new ones.

This problem persists as I continue to select different filters for columns like Name, Project, and Project Activity. It ends up cluttering the filtered data with incorrect items.

I am struggling to figure out how to prevent these wrong items from being added to the filtered columns.

Code

Within my HTML code, there are 5 columns:

<mat-table #table [dataSource]="dataSource" matSort matSortActive="work_date" matSortDirection="asc">
            <ng-container matColumnDef="create_by">
                <mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell>
                <mat-cell *matCellDef="let log"> {{ log.create_by }} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="project_id">
                <mat-header-cell ng-repeat="data in filtered = (list | filter: search)" *matHeaderCellDef
                    mat-sort-header>
                    Project ID </mat-header-cell>
                <mat-cell *matCellDef="let log"> {{ getSecondArrayItem(log.project_id)?.name }} </mat-cell>
            </ng-container>

            .....
            
        </mat-table>

The filtering logic is housed in the component's filterChange method, specifically in createFilter which handles the filtering of columns.

filterChange(filter, event) {
    // Filter change logic here
}

createFilter() {
    // Create filter function logic here
}

The connection between the application and the database is functioning correctly, allowing for filtering of one column at a time.

Answer №1

Let me share with you a solution that I came up with for a similar issue in one of my recent projects:

  1. Start by creating an input field for each column using reactive forms and subscribe to the valueChange event.

  2. Build a key-value object to store the search terms specific to each column, following the format {column1: filter1, column2: filter2} and so on.

  3. Update this object with the filtering criteria based on the changes detected in the valueChange event.

  4. Implement your custom filtering logic to override the default datasource filter.

  5. Ensure that your new filtering method correctly applies the filters according to the respective columns by utilizing a switch case.

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

The latest version of Angular2 has not been installed correctly

I decided to dive into the world of Angular2 and Express by cloning the repository from https://github.com/vladotesanovic/angular2-express-starter for my project. My goal was to start at a "Hello World" level, so I made it simpler by deleting all the file ...

The Yii2 CORS filter is throwing an error indicating the absence of the 'Access-Control-Allow-Origin' header

After reading through the information provided in this particular question, I have configured my rest controller behavior as follows: public function behaviors() { $behaviors = parent::behaviors(); $auth= $behaviors['authenticator'] = [ ...

What is the alternative parameter to use instead of onChange in React Router v4?

Having an issue with the onChange Prop in TypeScript and React JS: I am encountering an error message saying "No overload matched this call." <HashRouter> <Switch> <Route path="/" ...

Using Selenium WebDriver to Perform Drag and Drop Functionality on an Angular/Material Design Website

I've been attempting to automate the drag and drop event using Selenium Java WebDriver on a website built with Angular/Material design. Despite trying numerous approaches, none have been successful - there are no error messages, but the dragging and d ...

What is the best way to remove all attributes from one interface when comparing to another?

Consider the following two interfaces: interface A { a: number; b: string; } interface B { b: string; } I am interested in creating a new type that includes all the keys from interface A, but excludes any keys that are also present in interface B. ...

Angular 2 Date Input failing to bind to date input value

Having an issue with setting up a form as the Date input in my HTML is not binding to the object's date value, even though I am using [(ngModel)] Here is the HTML code snippet: <input type='date' #myDate [(ngModel)]='demoUser.date& ...

The jquery ui slider in Angular is not triggering the function when changes are made to the slider

I'm currently using Angular with jQuery UI slider and I have successfully initialized the slider and it is functioning properly. However, when I try to call another function from the change event, I encounter an error message: TypeError: this.getSe ...

Tips for creating the perfect ngrx state structure

Currently, I am working on adding a new feature state that includes a graph state with two subfeatures: node state and link state. Here is how I have implemented the graph state and reducer: export interface GraphState { [fromNode.featureKey]: fromNode ...

Angular project running Karma/Jasmine tests encounters failures when run on GitHub Action using Google Chrome on Ubuntu operating system

While working on my Angular project, I encountered an issue when trying to test it using Google Chrome with Karma & Jasmine in a GitHub Action. Google Chrome starts with multiple errors and eventually crashes after running some tests. Despite trying vario ...

The performance of Ionic 2 app views starts to lag

I'm currently working on an app with Ionic 2 that involves a timer functionality. Initially, the timer operates smoothly with instant updates. However, when viewed in Ionic View, the update frequency significantly decreases over time. Even when tested ...

Ensuring Function Parameter Usage in Typescript and Angular 5

Currently, I am developing a component using Angular 5 and Ionic 4. My objective is to include a Refresher event to hide the refresh spinner whenever the user triggers the final function to conceal the spinner. Provided below is an excerpt of my code: e ...

Elegantly intersect two types of functions in Typescript

Two function types are defined as follows: wrapPageElement?( args: WrapPageElementBrowserArgs<DataType, PageContext, LocationState>, options: PluginOptions ): React.ReactElement .. and .. wrapPageElement?( args: WrapPageElementNodeArgs<Data ...

Implementing atob in Angular's interface

Looking for a solution to a token storage issue, my initial thought is that interfaces might be the way to go. Presently, my login code looks like this: import { Component } from '@angular/core'; import { FormBuilder } from '@angular/forms&a ...

Converting an image file from the local directory to base64 encoding in an Angular application

Can someone help me convert a locally stored image named xyz.JPEG from the folder assets/img to base64 in Angular 8? I have attempted using FileReader and btoa, but it has not been successful. var reader = new FileReader(); var binaryString = reader.rea ...

Strategies for setting the output value for a defined generic type

Is there a way to create a function that accepts optional properties common across different types, while also requiring specific properties based on the generic type passed in? type Diff<T, U> = T extends U ? never : T type DiffTypes<T, U> = ...

I'm experiencing an issue with my Next.js Airbnb-inspired platform where I am unable to save a listing to my favorites

While working on my Next.js Airbnb clone project, I encountered an issue with adding a Listing to favorites. The heart button component's color does not change when clicked, despite receiving a success response. Moreover, the addition to favorites is ...

Adding custom type definitions for an untyped npm module in TypeScript 2

Despite attempting various methods recommended in other sources, I am struggling to configure a TypeScript project that utilizes an untyped NPM module. Below is a simplified example along with the steps I have taken. Let's imagine, for this demonstra ...

angular exploring the ins and outs of implementing nested child routing

Within my app-routing.module.ts file, I define the loading of child components like so: { path: 'account', loadChildren: () => import('./components/account/account.module').then((esm) => esm.AccountModule) }, Followin ...

Showing particular URL text upon opening a new window using JavaScript

I've encountered an intriguing scenario. In my application, there's a feature that triggers a new window/tab to open when a button is clicked. Upon opening, a predefined HTML page is shown to the user with a specific URL set. I'm curious abo ...

End the primary division post button activation within Angular 2

Is there a way to close the main div upon clicking a button that is located inside the same div? Below is my code snippet: index.html <div id="main"> <button type="button">Click Me!</button> </div> hello.component.ts import ...