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 behavior in Angular where updates to arrays in child components do not reflect the data passed from the parent is known as "

My child component is not listening for changes in data from the parent when using ArrayObjectParser. Any ideas on how to fix this issue? Please assist me. import { Component, OnInit, Inject, ViewChild, Input } from '@angular/core'; import { Form ...

Customizing font color upon hover in Next.js and Tailwind.css

Recently, I developed a Navbar component that displays a purple link when navigating to pages like Home or Projects. The issue arises when the background color is light; in this case, the link turns green on hover instead of staying purple. How would I adj ...

What type is the appropriate choice for this handler?

I´m struggling to select the right type for this particular function. It serves as an async handler for express js in a project that utilizes typescript and eslint for linting with specific rules. export function asyncHandler( handler: any ): (req: Requ ...

What is the process of implementing filters and search functionality in Vue.js tables?

I'm currently delving into Vue.js while constructing a Single Page Application. I am curious about how to integrate filters and search functionality using an input tag. Additionally, I'm looking to implement a feature where clicking on a name in ...

What is the best way to format this DateTime for a more visually appealing appearance within an Angular Material <mat-card-subtitle>?

My date looks like this: 2000-12-16T00:00:00 When displayed in Material code (as the publish_date): <mat-card *ngFor="let book of bookItems"> <mat-card-header > <mat-card-title>{{book.title | titlecase}}</mat-card-title> ...

Encountering an uncaught SyntaxError due to an unexpected token < while working with AngularJS2 on a local

I am currently facing an issue while trying to run my angularjs2 project locally using nodejs. I can successfully run it using npm start but encountering errors when attempting to use node app.js. The error message that pops up states: "systemjs.config.js ...

The "number" input type is functioning correctly on Chrome, but on Firefox, it is accepting characters other than numbers

While developing in Angular, I encountered a challenge where I needed to create an input that only accepts numeric characters. Initially, I tried using type="number" which worked perfectly in Google Chrome but surprisingly allowed non-numeric characters ...

What is the process for incorporating personalized variables into the Material Ui Theme?

In the process of developing a react app with TypeScript and Material UI, I encountered an issue while attempting to define custom types for my themes. The error message I received is as follows: TS2322: Type '{ mode: "dark"; background: { default: s ...

Steps to trigger pipe activation in Angular when the model is updated:1. Execute the

I have a unique filter pipe that allows me to filter an array of objects. This filter pipe has a dependency injection through a service. The service contains the model data filterService.data. Is there a way to activate this pipe in the template only when ...

Unpacking data types from an array of classes in TypeScript: A step-by-step guide

I am working on a function that takes an array or rest of Typescript classes as input and resolves, returning their instances. However, I'm struggling to ensure correct typing for it. If I take one class as an example: class Base { isBase = true ...

Ways of modifying the readonly and required attributes of an HTML element using Angular2 Typescript

I am facing an issue with changing input field attributes back and forth in some of my components. I have a code that successfully changes the readonly attribute as needed. However, when trying to change the required attribute, Angular2 still considers the ...

Finding the number of elements in a FirebaseListObservable involves accessing the `length` property

One of the tasks in my Angular 2 application involves retrieving data from a Firebase database and storing it in a FirebaseListObservable. I have a method called getStatus that is supposed to determine the number of elements in this FirebaseListObservable. ...

The Angular application has been successfully deployed on a Tomcat server as a war

I am planning to deploy a single page application (SPA) developed in Angular, along with various static files like *.css, .js, /assets/, all packed inside a war file on Tomcat. The issue I am facing is that whenever a user enters a path that does not corr ...

Ensuring the selected date matches any consecutive dates within the dates array in Angular

Imagine if 01/01/2022 is chosen from the input field, and my array of dates looks something like this: ['31/12/2021', '01/11/2021', '02/01/2022'...] In this scenario, when '31/12/2021' and '02/01/2022' are ...

update the value of a specific document in Firestore by specifying its

Is there a way to update document values in a Firestore collection for multiple records without manually specifying each document ID? Currently, I have a method that works for updating individual documents using their IDs, but what if I need to update a la ...

Can builtins like DOM globals be explicitly imported?

The present situation includes the utilization of rollup (as well as iife parameters), but I am hesitant about whether it is solely related to rollup or typescript. My objective is to achieve something similar to this: import { document } from "[wherever ...

React Material-UI - Mobile-friendly Masonry Layout

I'm new to working with React and I'm currently exploring how to create a Masonry image grid that is responsive for mobile devices. The goal is to have the images stack on top of each other in mobile view while maintaining the classic Masonry gri ...

There was an error due to a TypeError: The 'page' property cannot be read because it is undefined

Can anyone assist me with an Angular issue I'm facing? I've been working on integrating server-side pagination, but no matter how many times I revise my code, I keep encountering the same error message: ERROR TypeError: Cannot read properties o ...

Steps for selectively targeting and updating a group of properties in a TypeScript class

Is there a way to consolidate this code into one function that can handle all the tasks below? I'm adding more text here to meet the requirements and hoping for a solution. Thank you! TypeScript is an amazing language that differs slightly from JavaS ...

Understanding Typescript in Next.js components: Deciphering the purpose behind each segment

Consider the following function: type User = { id: string, name: string } interface Props { user: User; } export const getUserInfo: GetUserInfo<User> = async ({ user }: Props) => { const userData = await fetchUser(user.id); return ...