角度材质 - 自定义列过滤器和默认过滤器不能一起工作

问题描述

列过滤器工作得很好,但认过滤器(输入字段搜索)根本不起作用。我尝试了几件事,但没有任何效果。 我希望我的输入字段具有搜索两个列的认行为,即 allAssociates 和 dept 列以及各个列过滤器。 它也不会抛出任何错误自定义列过滤器参考来自所以我没有包括在这里https://www.freakyjolly.com/angular-material-table-custom-filter-using-select-box/#Adding_Filters_on_Table

filterTable 方法没有按预期工作 我将不胜感激任何建议..

完整代码https://stackblitz.com/edit/angular-material-b6qdyt?file=app%2Fapp.component.html

分享以下片段:

HTML

<div>
  <mat-form-field 
    *ngFor="let filter of filterSelectObj" 
    style="margin-left: 15px;">
    <mat-label> Filter {{filter.name}} </mat-label>
    <select 
      matNativeControl 
      name="{{filter.columnProp}}" 
      [(ngModel)]="filter.modelValue" 
      (change)="filterChange(filter,$event)">
      <option value=""> All </option>
      <option 
        [value]="item" 
        *ngFor="let item of filter.options">
        {{item}}
      </option>
    </select>
  </mat-form-field>
  <mat-icon>search</mat-icon>
  <input 
    type="text" 
    placeholder="All Associates/Dept" 
    #input 
    (keyUp)="filterTable($event.target.value)"> &nbsp;
  <button 
    mat-stroked-button
    color="warn" 
    (click)="resetFilters(input)">
    Reset
  </button>
</div>

TS 文件

ngOnInit() {
  //fetch data from Service
  const deptData = this.deptService.getData();
  this.dataSource = new MatTableDataSource(deptData);
  this.dataSource.filterPredicate = this.createFilter();
  this.filterSelectObj.filter((o) => {
    o.options = this.getFilterObject(deptData,o.columnProp);
  });
}

filterTable(input: string) {
  this.dataSource.filterPredicate =
    (data: DepartmentData,f: string) => !f || (data.allAssociates || data.dept) == f;
  input = input.trim(); // Remove whitespace
  input = input.toLowerCase(); // MatTableDataSource defaults to lowercase matches
  this.dataSource.filter = input;
}

解决方法

好的。我在您的实施中发现了两个问题。

  1. 在模板中,当要绑定到的实际事件名称为 (keyUp) 时,您将绑定到 (keyup)

  2. 你的谓词函数有问题。应该是这样的:

    this.dataSource.filterPredicate = (data: DepartmentData,f: string) => !f || data.allAssociates.toLowerCase().includes(f) || data.dept.toLowerCase().includes(f.toLowerCase());

解决这两个问题应该会让它开始为你工作。

这是一个Working Sample StackBlitz供您参考。