简体   繁体   中英

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"

You can use a search pipe on a table:

在此处输入图像描述

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])));
  }

}

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)

  }

  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM