What is the correct method for adjusting the filterPredicate in Angular materials?

Having trouble overriding the filterPredicate in my table with phone numbers and states. The filtering is working, but there's a bug where results for "UNASSIGNED" show up when I filter for "ASSIGNED". Can someone assist me with the correct syntax for overwriting the filterPredicate?

https://i.sstatic.net/wOWtB.png

Here's a snippet of the HTML:

<table mat-table [dataSource]="dataSource">
    <ng-container matColumnDef="telefonnummer">
      <th mat-header-cell *matHeaderCellDef> Telefonnummer </th>
      <td mat-cell *matCellDef="let element"> {{element.areaCode.prefix}}-{{element.areaCode.base}}- 
   {{element.extension}} </td>
    </ng-container>

    <ng-container matColumnDef="status">
      <th mat-header-cell *matHeaderCellDef> Status </th>
      <td mat-cell *matCellDef="let element"> {{element.phoneNumberType}} </td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns; sticky: true"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>

And a part of the TypeScript class:

displayedColumns: string[] = ['telefonnummer', 'status'];

products = [];

dataSource = new MatTableDataSource<any>(this.products);

constructor(private httpClient: HttpClient) {
    this.getAllNumbers();
}

@ViewChild(MatPaginator, {static: true}) paginator: MatPaginator;

ngOnInit() {
    this.dataSource.paginator = this.paginator;

    this.dataSource.filterPredicate = (data: any, filter: string) => {
      let matchFound = false;
      if (data === filter) {
          matchFound = true;
      }
  return matchFound;
};
}

If anyone can offer guidance, it would be greatly appreciated!

Answer №1

Using filters based on the strings assigned and unassigned may not be suitable in this scenario. If your table expands with more columns allowing users to input either assigned or unassigned, your filtering process could become inaccurate.

However, if that isn't a concern (considering the table only has two columns with one dedicated to numbers), you can apply the following filtering logic using the column status:

this.dataSource.filterPredicate = (data, filter): boolean => {
  const transformedFilter = filter.trim().toLowerCase();
  if (data.status.trim().toLowerCase() === transformedFilter) {
    return true;
  } else if (data.telefonnummer.trim().toLowerCase() === transformedFilter) {
    return true;
  };
  return false;
} 

This snippet provides a straightforward explanation of the process.

p.s. It's important to note that telefonnummer.trim() may result in an error if telefonnummer is a number rather than a string. Additionally, ensure to validate status.trim() to prevent any potential issues.

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

Is there a way to determine if a browser's Storage object is localStorage or sessionStorage in order to effectively handle static and dynamic secret keys within a client?

I have developed a customizable storage service where an example is getExpirableStorage(getSecureStorage(getLocalStorage() | getSessionStorage())) in typescript/javascript. When implementing getSecureStorage, I used a static cipher key to encrypt every ke ...

The process of invoking a function within another function in TypeScript Angular

Just starting out with Angular 2, I've written the following code in my Angular project: export class TestClass { constructor() { this.initMap(); } initMap() { this.marker.addListener('dragend', this.onMarkerDr ...

How come I am unable to make the allTodos property private in the service when it is populated with data from an http request

I have a task-list component and I want to populate it with a task-service. This service fetches the data from a local JSON file. Here is my task-list component: import 'zone.js/dist/zone'; import { Component } from '@angular/core'; im ...

Discover the inferred arguments of methods declared on an object in TypeScript

Assume I have methods that are defined in the following way: const methods = { methodOne(a: string) { return a; }, methodTwo(a: number) { return a; }, methodThree() {} } as const; I am able to deduce the type of methods: type MethodDefinitio ...

Resolving the CORS predicament caused by the ionic/angular's HTTP interceptor

I am currently using Ionic for both web and mobile development. However, I have encountered a CORS issue when integrating it with an HTTPS URL. Interestingly, the issue seems to be resolved after removing the HTTP interceptor. Nevertheless, I am seeking a ...

An issue with Typescript expressions failing to evaluate has been identified in the Angular 8 Router when running

I have encountered an issue while attempting to execute a TypeScript expression within the router module of my Angular application. The expression I am trying to evaluate is as follows: const check: any = window.innerWidth > 600 ? RouteOneComponent : Ro ...

How to effectively utilize ViewChildren _results in Angular 4?

I'm working with a list of checkboxes that are generated within an ngFor loop: <md-checkbox #hangcheck [id]="hangout?.$key" class="mychecks" > I'm Interested </md-checkbox> To reference these checkb ...

Is there a way to integrate the AuthState TypeScript Interface into the react-oidc-context Node package for testing in Next.js?

We are currently working on a Next.js application that utilizes the react-oidc-context Node module for authentication with ADFS. During our testing phase using Vitest, we encountered the following error: TypeError: Cannot read properties of undefined (rea ...

Conflicting TypeScript enum types: numbers and numbers in NestJS/ExpressJS

Incorporating types into my NestJS server has been a priority. After creating a controller (a route for those who prefer Express), I attempted to define the type for params: public async getAllMessages( @Query('startDate', ValidateDate) start ...

Ways to extract a Bearer Token from an Authorization Header using JavaScript (Angular 2/4)

When working with JavaScript, I have successfully implemented a method for authenticating to my server using an http post request. Upon receiving a response from the server, it includes a JWT in an Authorization header like this: Authorization: Bearer my ...

When utilizing an import statement in TypeScript, it is not possible to access ethers.js providers

While trying to utilize ethers.js provider in my TypeScript project using ts-node, I encountered the following issue: import { ethers } from "ethers"; const provider = new ethers.providers.JsonRpcProvider(url); The error message displayed was: ...

What is the approach to merge an inner observable in RxJs with the outer observable and produce a single array as output

Whenever I execute the following code: timer(1000).pipe( expand(() => of('a')), take(3) ) .subscribe(data => alert(data)); I receive three alerts: one with 0, another with 'a', and a third one also with 'a'. I wo ...

ngx-graphs -> ngx-graphs-bar-vertical x-axis labels with multiple lines

I'm using 'ngx-charts' with Angular, and I have encountered an issue with long text on my X axis labels. The text overflows and displays three dots instead of wrapping onto multiple lines. Is there a way to make the text wrap onto multiple l ...

Access NgModel from NgForm

Is there a way to access the NgModel of a FormControl retrieved from the NgForm.controls object within its parent form, or directly from the form itself? Upon form submission, I pass the form as a parameter to a custom function: <form #myForm="ngForm" ...

What is the best way to utilize ngFor for iterating through a Map variable of classes in TypeScript?

In my TypeScript file, I have a class named `myMap` that contains a variable called `navList`, which is of type Map<string, string> and holds multiple key-value pairs. I am currently attempting to iterate over the values stored in `navList` within my ...

Angular's HttpClient makes sure to wait for the HTTP requests to complete

Initializing arrays with the call this.Reload.All() is causing confusion and breaking the service due to multiple asynchronous calls. I am looking for a synchronous solution where each call waits for its response before proceeding to the next one. How can ...

The minimum and maximum validation functions are triggered when I am not utilizing array controls, but they do not seem to work when I use array controls

Take a look at the stack blitz example where min and max validation is triggered: https://stackblitz.com/edit/angular-mat-form-field-icrmfw However, in the following stack blitz with an array of the same controls, the validation does not seem to be worki ...

Exploring the possibilities of combining colspan and ngFor in an Angular material 6 table

Angular Material is being utilized for table rendering in my project. https://i.sstatic.net/uwYG2.png Code: <ng-container matColumnDef="type"> <th mat-header-cell *matHeaderCellDef> Workout type </th> <td mat-cell *matCellDef= ...

What impact does the size of the unpacked files have on the overall minified size of an npm package?

I've been working on shrinking the size of an npm package I created, and I've successfully reduced the unpacked size to around 210kb. https://www.npmjs.com/package/@agile-ts/core/v/0.0.12 <- 210kb https://www.npmjs.com/package/@agile-ts/core ...

Dynamic Angular Pipes

Having trouble building a dynamic pipe, even though the pipes are included in the app module provider, resulting in a NullInjector error. I recommend opening the Console window in Developer options to view the error details. A demo link has been provided ...