简体   繁体   English

Angular 表搜索过滤器

[英]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我有一个需要过滤的表,但有些值是表中的 null 值,所以我不能在返回时使用 tolowercase()

Error: Cannot read property tolowercase() of null错误:无法读取 null 的 tolowercase() 属性

I need to filter the selected rows in the table irrespective of the null values.无论 null 值如何,我都需要过滤表中的选定行。

Also, the search must return the row even though one value in the row is null此外,搜索必须返回该行,即使该行中的一个值为 null

Note: I am using a FilterPredicate注意:我使用的是 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 HTML 代码

 <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.预期结果:过滤signingName、serviceName、branchName。

Actual result: Due to null values,I get " Cannot read property toLowerCase() of null"实际结果:由于 null 值,我得到“无法读取属性 toLowerCase() of null”

You can use a search pipe on a table:您可以在表上使用搜索 pipe:

在此处输入图像描述

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.如果字段的值为 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)

  }

  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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