Search functionality in Angular using column-based filtering algorithm

Take a look at my table view below. Each column has its own search function.

My current issue is that when I type in one column, the same text appears in other columns as well. To solve this problem, I have implemented the following code:

        <tr>
            <th *ngFor="let head of headElements; let i = index" scope="col">
                <h5 class="text-color">{{head}}</h5>
                <div class="md-form mb-0">
                    <input [(ngModel)]="searchText[i]" type="text" class="form-control" 
                      id="search_{{i}}" mdbInput />
                    <label for="search_{{i}}">Search</label>
                </div>
            </th>
        </tr>

By using [(ngModel)]="searchText[i]" or [(ngModel)]="searchText[head]", I can input different text into different boxes.

However, I am having trouble accessing the typed text in the filter: searchText;

Here is my code for viewing the table data:

    <tbody>
        <tr *ngFor="let el of elements | filter : searchText; let i = index" mdbWavesEffect>
            <td class="p-2" *ngIf="i+1 >= mdbTablePagination.firstItemIndex && i < mdbTablePagination.lastItemIndex"
                scope="row">{{el.firstName}} {{el.middleName}} {{el.lastName}}</td>
            <td class="p-2" *ngIf="i+1 >= mdbTablePagination.firstItemIndex && i < mdbTablePagination.lastItemIndex">
                {{el.mobileNumber}}</td>
            <td class="p-2" *ngIf="i+1 >= mdbTablePagination.firstItemIndex && i < mdbTablePagination.lastItemIndex">
                {{el.joiningYear}}</td>
            <td class="p-2" *ngIf="i+1 >= mdbTablePagination.firstItemIndex && i < mdbTablePagination.lastItemIndex">
                {{el.emailId}}</td>
            <td class="p-2" *ngIf="i+1 >= mdbTablePagination.firstItemIndex && i < mdbTablePagination.lastItemIndex">
                {{el.designation}}</td>
        </tr>
    </tbody>

In addition to this, I have declared searchText: any = []; in the component.ts file to avoid any undefined errors.

Lastly, here is my filter pipe code:

  if (!employees || !searchTerm) {
    return employees;
  }
  return employees.filter(employee =>
    employee.mobileNumber.toLowerCase().indexOf(searchTerm) !== -1);

}

Answer №1

Instead of relying on the filter pipe for <tr>, consider using the change event listener on your <input>.

<tr>
        <th *ngFor="let head of headElements; let i = index" scope="col">
            <h5 class="text-color">{{head}}</h5>
            <div class="md-form mb-0">
                <input [(ngModel)]="searchText[i]" (change)="filterElements(searchText[i])" type="text" class="form-control" 
                  id="search_{{i}}" mdbInput />
                <label for="search_{{i}}">Search</label>
            </div>
        </th>
    </tr>

In your component class:

private elementsCopy = Object.assign({}, this.elements);
public filterElements(searchTerm){
    if (!this.elementsCopy || !searchTerm) {
        return this.elementsCopy ;
      }
  return this.elementsCopy.filter(employee =>
    employee.mobileNumber.toLowerCase().indexOf(searchTerm) !== -1);

}

I trust this suggestion proves useful.

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 web server is now serving Index.html instead of main.js for AngularJS 2

Transitioning from an angular1 application to an angular2 one, I encountered an error after removing the ng-app directive and adding the system.config: Error: SyntaxError: Unexpected token < Evaluating https://localhost:8080/contents/app/main.js Error ...

Embedding a TypeScript React component within another one

Currently, I'm facing an issue with nesting a TypeScript React component within another one, as it's causing type errors. The problem seems to be that all props need to be added to the parent interface? Is there a way to handle this situation wi ...

Include a string in every tuple

I am trying to define a new type: type myNewType = 'value-1' | 'value-2' | 'value-3' Is there a way to create another type like this? type myNewType2 = '1' | '2' | '3' However, I want the outpu ...

Error in React.tsx Material UI Tab - Avoid using curly braces "{}" as a data type

Currently, I am working on a React TS project and facing an issue while trying to import the Material UI tabs for scrollable functionality. The specific Tabs/Scrollable Tabs example from Material-UI documentation is what I'm referring to: https://mate ...

Creating a mongoDB query that matches elements in an array of subdocuments with elements in a Typescript Array

In my database, I have stored various Events using mongoDB. Each event comes with multiple fields, including an array of genres, which consists of subdocuments like {genre and subGenre}. For instance, an event could be classified as {genre: "music", subGe ...

I am excited to incorporate superagent into my TypeScript-enabled React project

Currently, I am attempting to integrate superagent into my TypeScript-ed React project. I have been following a tutorial on TypeScript with React and encountered some difficulties when using superagent for server requests, despite successfully utilizing ma ...

Can you generate two distinct arrays by clicking create?

My website has a customer page called customer.html: <app-z-grid title="Tip korisnika" [restPath]="'customertype'" (fillDetailParent)="reinit($event)"></app-z-grid> <app-z-grid title="Podtip korisnika" [path]='"custome ...

Error in Angular: trying to access property 'genre' of an undefined object

I am currently developing a simple app inspired by a tour of heroes (official angular tutorial). However, I have encountered an issue that I cannot seem to resolve, possibly due to my lack of understanding in basic programming concepts. Here is the code s ...

Vite HMR causes Vue component to exceed the maximum number of recursive updates

After making changes to a nested component in Vue and saving it, I noticed that the Vite HMR kept reloading the component, resulting in a warning from Vue: Maximum recursive updates exceeded... Check out the online demo on stackblitz. Make a change in Chi ...

Create a fresh Ionic 3 application utilizing Angular 4

After installing Ionic 3.6, which supports Angular 4.0.1, I encountered a problem. When creating a new project with the command ionic start newProject, it defaults to using Angular 5. This is evident from the package.json file below, showing angular-ionic ...

Having trouble with MUI auto import suggestions in my Next.js 13 project on VS Code

I'm currently developing a project using Next.js 13 and have installed MUI. However, I am encountering an issue where VS Code is not providing auto imports from the @mui/material library, as shown in the attached screenshot. https://i.stack.imgur.com ...

What is the process for displaying an enum in an Angular Mat Form Field?

Hey there! Check out my awesome app - My app. I need help with writing a Java/Visual Studio script for my app. How can I make it so that when I click on "Upgrade" for the id 1, the "Account" row displays CASH as the default value? Right now, no value is sh ...

A guide on dynamically showcasing/summoning icons in react by utilizing array data

QUESTION: 1 (SOLVED!) https://i.stack.imgur.com/1M1K7.png What is the best way to display icons based on an array of data codes? const data = [{ img: '01d' }, { img: '02d' }] if(data) { data.map((item) => ( <img src={`./ ...

Is there a compelling case for implementing Meteor in 2017?

Back in the day, Meteor was expected to revolutionize web development on node by simplifying the process of creating interactive applications. Though I'm not well-versed in its history, it seems like most of the development effort has shifted elsewher ...

After the initial submission, the Bootstrap placeholder for the Select Option is only displayed

I'm attempting to create a placeholder for my dropdown with multiple options using Angular and Bootstrap. However, it seems like I may be doing something incorrectly. I created an option for a placeholder such as please select and placed it at the top ...

Creating a filter with Django Rest Framework and Angular 11 by utilizing multiple data values

I've been encountering difficulties with searching and filtering in my current project setup. The technologies I'm using include Django Rest Framework and PostgreSQL for the backend, as well as Angular 11 for the frontend. Here is a snippet of my ...

Ensuring the validation of JSON schemas with dynamically generated keys using Typescript

I have a directory called 'schemas' that holds various JSON files containing different schemas. For instance, /schemas/banana-schema.json { "$schema": "http://json-schema.org/draft-06/schema", "type": "object", "properties": { "banan ...

Ways to merge two distinct arrays [Angular and Typescript]

I am faced with a task where I need to merge two array lists in order to create a new array list that contains all the values associated with a common UUID in both lists. The final list should include all the values linked to the UUID in each of the origin ...

Discovering ways to fetch an array of objects using object and arrays in JavaScript

When comparing an array of objects with a single object and listing the arrays in JavaScript, specific conditions need to be met to retrieve the array of objects: If the itemvalue and idvalue are the same, check if the arrobj cid has the same codevalue ...

What is the best way to utilize a single npm module in multiple TypeScript files?

Question: I keep encountering the error message "error TS2451: Cannot redeclare block-scoped variable 'os'" when I try to import the same npm module in multiple TypeScript files and run the TypeScript compiler tsc. Here is an overview of my proj ...