ngx-datatables in Angular is experiencing issues with its filtering options

Having trouble implementing a filter option in ngx-datatables for all columns. I've written the code but it's not functioning correctly. Can anyone help me identify where I went wrong and find solutions?

app.component.html:

    <label> Name </label>
    <input
      #name
      id="search"
      type="text"
      class="form-control"
      placeholder="Search"
      aria-label="Search"
      aria-describedby="basic-addon1"
    />

    <label> Company </label>
    <input
      #company
      id="search"
      type="text"
      class="form-control"
      placeholder="Search"
      aria-label="Search"
      aria-describedby="basic-addon1"
    />

    <label> Date  </label>
    <input
      #date
      id="search"
      type="text"
      class="form-control"
      placeholder="Search"
      aria-label="Search"
      aria-describedby="basic-addon1"
    />


    <button (click)="updateTable()"> Search </button> 

  <ngx-datatable #table class="bootstrap ngx-datatable" [columns]="columns" [rows]="rows" [columnMode]="'force'"
    [headerHeight]="35" [rowHeight]="'auto'" [footerHeight]="50" [limit]="10">
  </ngx-datatable>

app.component.ts:

  updateTable() { 
      let filterName = this.name.nativeElement.value
      .toString()
      .toLowerCase()
      .trim();
      let filterCompany = this.company.nativeElement.value
      .toString()
      .toLowerCase()
      .trim();
      let filterDate = this.date.nativeElement.value
      .toString()
      .toLowerCase()
      .trim();

  this.rows = this.filteredData.filter(item => {
     for (let i = 0; i < this.columnsWithSearch.length; i++) {
    var colValue = item[this.columnsWithSearch[i]];

    if (
      !filterName ||
      !filterCompany ||
      !filterDate ||
      (!!colValue &&
        colValue
          .toString()
          .toLowerCase()
          .indexOf(filterName) !== -1)
    ) {
      return true;
    }
  }
});
}

Demo: https://stackblitz.com/edit/angular-ngx-datatables-filter-all-columns-evltmj?file=src%2Fapp%2Fapp.component.ts

Answer №1

Your primary concern lies in the condition you are using:

if (
  !filterName ||
  !filterCompany ||
  !filterDate ||
  (!!colValue &&
    colValue
      .toString()
      .toLowerCase()
      .indexOf(filterName) !== -1)
)

If any of the three fields (filterName, filterCompany, or filterDate) are empty, your filter will return true. Moreover, you are only checking for a match with filterName.

To simplify your code, you can replace these three variables with an object

filter = {name: '', company: '', date: ''}
and update your condition to:

const filterValue = filter[this.columnsWithSearch[i]];
if (
  !filterValue ||
  (!!colValue &&
    colValue
      .toString()
      .toLowerCase()
      .indexOf(filterValue) !== -1)
) {
  return true;
}

For cleaner and more efficient code, consider exploring Angular pipes, which can optimize your system and enable real-time searching capabilities.

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

"Encountered a floating-point issue when trying to read an Excel file with

When a user uploads an Excel file that contains decimal, string, and Unicode characters, I am encountering an issue with floating point errors when reading certain decimal values. For instance, a number like 0.15 is being read as 0.150000000002 in some c ...

Is there a way to properly install angular cli that is compatible with node version 13.14.0?

Running Windows 7, I attempted to install an outdated version of node - specifically node 13.14.0. However, when trying to install the Angular CLI with the command "npm i -g @angular/cli", an error occurred. Can anyone advise on what steps I should take ne ...

Passing dynamic values to nested components within an ngFor loop in Angular

I'm currently facing an issue with a child component inside a ngFor loop where I need to pass dynamic values. Here is what I have attempted so far, but it doesn't seem to be working as expected <div *ngFor="let item of clientOtherDetails& ...

Error: The module 'AppModule' has encountered an unexpected value 'CalendarComponent'. To resolve this issue, please include a @Pipe/@Directive/@Component annotation

Recently, I started working with Angular 2 and wanted to incorporate the 'schedule' feature from Primeng. To do so, I installed its package and added the calendarComponent in my app.module.ts file as shown below: import { BrowserModule } from &a ...

Guide to redirecting to an ASP application using POST data from Angular 5

I'm currently working on integrating a payment gateway into my Angular application. This particular payment gateway is built using ASP. The instructions provided by the payment gateway provider instruct me to submit a form as a POST request to a spec ...

Leverage the globalDependencies feature in Angular2 to utilize Typescript tsd files

I am attempting to incorporate typescript tsd's from DefinitelyTyped into an Angular2 project (RC.0), but encountering issues with loading global dependencies properly: typings install --save dt~hellojs --global --save npm install --save hellojs Her ...

Issue with displaying labels in ChartJS plugin on Ionic 3 platform

Currently, I am using Ionic 3 and have implemented a bar chart in my project. However, I am facing an issue where the data labels are not being displayed next to the bars on the chart. This is similar to the problem discussed in this question how to displa ...

Oops! Angular2 couldn't find a provider for HttpHandler

I have been working on implementing HttpCache through an interceptor. Below is the code snippet for caching-interceptor.service.ts: import { HttpRequest, HttpResponse, HttpInterceptor, HttpHandler, HttpEvent } from '@angular/common/http' import ...

Iterate through controls to confirm the accuracy of the password输入 unique

Struggling a bit here since ControlGroup is no longer available. I need to ensure that two passwords match on the front end. this.updatePassordForm = _form.group({ matchingPassword: _form.group({ password: new FormControl('' ...

I'm looking to display the message between the specified start date and end date that is selected in the input field

Is it possible to utilize ngOnChange? <div> <label for="start">Start date:</label> <input type="time" name="starts" [(ngModel)]="starts"> <label for="end">End date: </label> <input type="time" name="end" [(ng ...

Unusual Behavior of *ngIf and jQuery in Angular 5: A curious case

I'm encountering a strange issue when using the expand-collapse feature of Bootstrap 4 with *ngIf for expansion and collapse. I noticed that the jQuery doesn't work when *ngIf is used, but it works fine when *ngIf is removed. HTML: <div cla ...

A guide to properly executing initialization functions in Angular with Electron

Currently, I am working with Angular and Electron. I have a Preferences object that I need to initialize (Preferences.init()) before any other code is executed. Is there a specific location in Angular or Electron where this initialization code should be pl ...

What is the process of including items in an Array?

I have been attempting to use the push method to add elements to an Array in Typescript, but strangely it doesn't seem to be working. The array just stays empty. Here's the code I have: list: Array<int> = Array(10) for(le ...

Exploring the implementation of Chain Map or Chain Filter within an Angular Http request that delivers a promise

I have a dataset in JSON format that I am working with, and I need to filter out specific key values using lodash. I want to reject multiple keys that I don't need. My initial approach is to either chain the map function and then use the reject funct ...

Tips for preventing the rxjs error "TypeError: Cannot read properties of undefined" in the Angular framework

When I try to open the page in Angular, I encounter this error: core.mjs:6485 ERROR TypeError: Cannot read properties of undefined (reading 'getDocumentContent') In my Angular component, I have an observable like this: selectedDocument$ = this.s ...

Is it possible that multiple identical queries are being executed in succession when adjusting the amount of data being displayed?

Why do multiple identical GET requests get executed when changing the data amount? [HPM] GET /api/users/get_all?search=&order=asc&pageSize=25&page=1 -> http://localhost:5000 GET /api/users/get_all?search=&order=asc&pageSize=2 ...

Passing an array of items as a property to a child component in React with Typescript is not possible

In my project, I have multiple classes designed with create-react-app. I am trying to send an array of objects to child components as illustrated below. Items.tsx import * as React from 'react'; import ItemTable from './ItemTable'; imp ...

Ways to categorize by a particular date

const vehicleDetails = [ { "record_id": "2ff8212f-5ec9-4453-b1f3-91840a3fb152", "status_date_activity": { "On Rent": 1662021991000 } }, { "record_id": "c8c1 ...

Angular functions fail to update the loop variable

Using the documentSnapshot function in Firestore to verify the existence of a document. The function is executed in a loop up to a value of 5. However, even though the function runs 5 times, the value of 'i' always reflects the last value. The ...

Type of object is unidentified in Vuejs with Typescript error code ts(2571)

Currently, I am facing a challenge with storing JSON data in a variable within my Vue project. Below is the code snippet used to upload and store the file: <input type="file" id="file" ref="fileSelect" class="custom- ...