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

The 'checked' property cannot be bound to 'mat-button-toggle' as it is not recognized as a valid property in Angular 9

I am encountering an issue with my Angular 9 application. I have integrated angular-material and imported the MatCheckboxModule correctly in the module. Here is the version of the material package I am using: "@angular/material": "^10.2.0&q ...

Easily showcase a limitless number of items within a 10-column grid using Bootstrap!

This is the code snippet: <div *ngFor="let minute of state.minutes.specificMinutes.selectedMinutes | keyvalue" class="col-sm-1 checkbox-container"> <div class="custom-control custom-checkbox"> <input type="checkbox" (click)="state.m ...

Error Arises When Making Selection in PrimeNG's P-ListBox Component

Whenever I choose an item from my listbox module, I encounter an error where the value is being returned as an object instead of an array in my listbox.js file from p-listbox by PrimeNG. HTML: <p-listbox formControlName="programType" [options]="phoneT ...

Is it possible to identify and differentiate objects based on their interface types in JavaScript/TypeScript?

Incorporating a library that defines the following interfaces: LocalUser { data { value: LocalDataValue }, ...various other methods etc... } RemoteUser { data { value: RemoteDataValue }, ...various other methods etc... } A User is then ...

When utilizing express-handlebars to render, the error message "req.next() is not a valid function

Trying to display the login page of a web application. Developed using TypeScript, node.js, express, and express-handlebars The code being executed is as follows: import exphbs = require("express-handlebars"); import cookieParser = require(&quo ...

How can I use Angular to download the HTML content of a component when a button is clicked?

Is there a way to generate and download an HTML report directly from a dialog box in Angular 13.2.5 without redirecting the user to a separate page? The dialog box collects user input, and I want a button labeled "Generate" at the bottom of the dialog box ...

Updating dynamically rendered component content with ngComponentOutlet in Angular 11: A comprehensive guide

I am working on an Angular 11 app that includes a menu generated from an array of objects with specific properties: { icon: CUSTOMER_ORDER_PROPERTIES.icon, iconColor: CUSTOMER_ORDER_PROPERTIES.color, label: 'Search Customer Order', routeB ...

Is it possible to access the generic type that a different generic type inherits in TypeScript?

I've developed an interface specifically designed for types capable of self-converting to IDBKey: interface IDBValidKeyConvertible<TConvertedDBValidKey extends IDBValidKey> { convertToIDBValidKey: () => TConvertedDBValidKey; } My goal n ...

Conflicting Transformation Properties Causing CSS Issues Within a Single Element

I'm currently working on a user interface where users can drag and drop a box with a red outline to position it on the screen within a black box. See the UI here Alternatively, users can also move the box by adjusting the inputs on the right side. ...

Oops! The 'map' property cannot be found in the type 'Observable<User>'

In my online shopping project that combines Angular and Firebase, I implemented the AuthGuard to verify user login status before accessing various links including ./check-out. However, I encountered an issue with importing map for Observable.User. All comp ...

The expected property 'label' is not found in the object type '{ handleClick: () => void; }', but it is required in the object type '{ handleClick: () => void; label: string; }'

I'm encountering difficulties when describing the types of my props. The issue arises with the following code: <PostButton handleClick={props.upvote}/> <PostButton2 handleClick={props.downvote}/> An error message is displayed: Pro ...

What is the method for sending a Post request using the "content type" value of "application/x-www-form-urlencoded"?

Need to send a request to the oAuth2 authentication server to obtain a token. The request works fine in postman but encountering issues when trying to make the same request from Angular 4. CORS configuration is correct as other requests are functioning p ...

Is there a way to receive a comprehensive report in case the deletion process encounters an error?

Currently, I am performing a delete operation with a filter based on 2 fields: const query = await Flow.deleteOne({ _id: flowId, permissions: currentUser!.id, }); After executing the delete operation, I inspect the query object to determine its su ...

Differences between Angular TS Lint onInit and ngOnInit

My TS Lint issue warned me to implement the OnInit interface and included a link to this page: https://angular.io/docs/ts/latest/guide/style-guide.html#!#09-01 I'm curious, what sets apart `onInit` from `ngOnInit`? Both seem to work just fine for me. ...

Util Deprecations resolved with TSLint Autofix

Is there a feature in VSCode that can automatically fix deprecations related to the util library? For example: if (isNullOrUndefined(this.api)) { Would be better written as: if (this.api === null || this.api === undefined) { While there isn't an ...

To continue receiving rxjs updates, kindly subscribe if the specified condition is met

Is there a way to check a condition before subscribing within the operator chain? Here's what I have: // parentElem:boolean = false; // the parent elem show/hide; let parentElem = false; // inside the ngAfterViewInit(); this.myForm.get('grandPa ...

The Vue component's TypeScript object prop type does not match the expected value

Having trouble with the type of Object properties in Vue Single File Components using TypeScript (created with Vue CLI 3)? Check out the example below to see the issue. The type of this.product is currently showing as (() => any) | ComputedOptions<a ...

Resolve the issue of text overflow in PrimeNG Turbo Table cells

When utilizing Primeng table and enabling the scrollable feature, the table is expected to display a scrollbar while ensuring that the text within the cells does not overflow. Unfortunately, this expected behavior is not occurring. To see an example of th ...

What is the reason for a class's attributes being considered undefined even after they have been previously set?

Within my code, there is a class called WorkspaceDatabase that stems from the Dynamic Tree Example. I have incorporated some debugging information to gain a clearer understanding of the issue at hand. The Issue: Upon entering the complete() function, an ...

Encountered issues with the BsModalService in displaying the modal functionality

I am encountering an issue while attempting to display a modal using a service. When I call the service from a button, everything works fine. However, I encounter an error when calling it from an error handler. TypeError: Cannot read property 'attach ...