带过滤角材料的复杂类型表

时间:2018-10-09 18:38:07

标签: html angular typescript angular-material angular5

我想将表与Angular Material一起使用,但是我无法过滤复杂类型(Branch.category)。实际过滤器仅适用于subjectName。

TS:

   export class Subject {
  id: Number = null;
  subjectName: String = '';
  branch: Branch = new Branch;
}

export class Branch {
  category: String = '';
}



displayedColumns: string[] = ['id', 'subjectName', 'category'];
dataSource;
subjects: Subject[];

constructor() {

this.subjects = [];
this.subjects.push({id:1, subjectName: 'Biology', branch: {category: 'science'}});
this.subjects.push({id:2, subjectName: 'physics', branch: {category: 'science'}});
this.subjects.push({id:3, subjectName: 'english', branch: {category: 'humanities'}});

this.dataSource = new MatTableDataSource(this.subjects);
}

applyFilter(filterValue: string) {
  console.log(filterValue);
  this.dataSource.filter = filterValue.trim().toLowerCase();
}

HTML:

<mat-form-field>
  <input matInput (keyup)="applyFilter($event.target.value)" placeholder="search">
</mat-form-field>

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

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

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

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

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let element; columns: displayedColumns;" 
    [ngClass]="{'highlight': selectedRowIndex == element.id}"
    (click)="highlight(element)"></tr>

</table>

我想制作两个单独的过滤器:subjectName和category。

1 个答案:

答案 0 :(得分:2)

欢迎使用StackOverflow,我想您可能想为数据表做一个自定义过滤器,可以通过覆盖数据源的filterPredicate属性来做到这一点,如下所示:

this.dataSource.filterPredicate = (data, filter) => {
  const customField = data.branch.category;
  return customField === filter; 
}

这只是您的一个小示例,可能需要一些修复程序才能工作。请让我知道它的适合程度,我们可以进行工作。您可以阅读文档以获取更多信息here

编辑:找到了这个Github issue,我认为它将对您有用。