Yasik raam
Yasik raam

Reputation: 61

Angular table search filter

I have a table which needs to be filtered but, some values are null values in the table so I can't use tolowercase() as it returns

Error: Cannot read property tolowercase() of null

I need to filter the selected rows in the table irrespective of the null values.

Also, the search must return the row even though one value in the row is null

Note: I am using a FilterPredicate

I have tried using Filter Predicate to filter the tables

Filter Predicate

 this.dataSourceProject.filterPredicate =function (p, filter: any) {

   if (filter.filterSelect == true) {

    return p.signingName.toLowerCase().includes(filter.values) || 

     p.serviceName.toLowerCase().includes(filter.values) || 

     p.branchName.toLowerCase().includes(filter.values)

  }

  }

Apply Filter

applyFilter(filterVal: string) {

    filterVal = filterVal.trim().toLowerCase(); 

    let filterValue: any = {
        values: filterVal,

        filterSelect:true
      }


      this.dataSourceProject.filter = filterValue;
    }

HTML CODE

 <mat-form-field>     

        <input matInput (keyup)="applyFilter($event.target.value)" 
        placeholder="Search" autocomplete="off">

 </mat-form-field>

Expected result: To Filter the signingName, serviceName, branchName.

Actual result: Due to null values ,I get " Cannot read property toLowerCase() of null"

Upvotes: 1

Views: 1939

Answers (2)

Quentin
Quentin

Reputation: 1933

You can use a search pipe on a table:

enter image description here

Stackblitz

SearchPipe:

@Pipe({
  name: 'search'
})
export class SearchPipe implements PipeTransform {

  transform(value: any, keys: string, term: string) {
    if (!term) {
      return value;
    }
    return (value || []).filter((item) => keys.split(',').some(key => item.hasOwnProperty(key) && new RegExp(term, 'gi').test(item[key])));
  }

}

Upvotes: 3

edkeveked
edkeveked

Reputation: 18371

A default empty string can be used in case the value of the field is null.

 this.dataSourceProject.filterPredicate =function (p, filter: any) {

   if (filter.filterSelect == true) {

    return (p.signingName || "").toLowerCase().includes(filter.values) || 

     (p.serviceName || "").toLowerCase().includes(filter.values) || 

     (p.branchName || "").toLowerCase().includes(filter.values)

  }

  }

Upvotes: 1

Related Questions