【问题标题】:How to edit angular materials filterPredicate the right way?如何以正确的方式编辑 angular material filterPredicate?
【发布时间】:2020-02-05 01:42:43
【问题描述】:

由于我在互联网上找不到很多解释如何以正确方式覆盖 filterPredicate 的示例,所以我决定在这里提问。正如您在照片中看到的那样,我有一张表格,里面有不同状态的电话号码。

过滤有效,但有一个小错误我不知道如何修复。当我过滤“ASSIGNED”时,“UNASSIGNED”和“ASSIGNED”的结果将显示给我。 “UNASSIGNED”,因为它包含“ASSIGNED”。

所以我发现我需要覆盖 filterPredicate。我尝试了几次,但不太了解其中的语法。你能帮我做什么吗?

这就是html(仅必要部分):

<table mat-table [dataSource]="dataSource">

    <!-- Position Column -->
    <ng-container matColumnDef="telefonnummer">
      <th mat-header-cell *matHeaderCellDef> Telefonnummer </th>
      <td mat-cell *matCellDef="let element"> {{element.areaCode.prefix}}-{{element.areaCode.base}}- 
   {{element.extension}} </td>
    </ng-container>

    <!-- Name Column -->
    <ng-container matColumnDef="status">
      <th mat-header-cell *matHeaderCellDef> Status </th>
      <td mat-cell *matCellDef="let element"> {{element.phoneNumberType}} </td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns; sticky: true"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>

那是我的 ts 类(只有必要的部分):

displayedColumns: string[] = ['telefonnummer', 'status'];

products = [];

dataSource = new MatTableDataSource<any>(this.products);

constructor(private httpClient: HttpClient) {
    this.getAllNumbers();
}

@ViewChild(MatPaginator, {static: true}) paginator: MatPaginator;

ngOnInit() {
    this.dataSource.paginator = this.paginator;

    this.dataSource.filterPredicate = (data: any, filter: string) => {
      let matchFound = false;
      if (data === filter) {
          matchFound = true;
      }
  return matchFound;
};
}

感谢您的每一个帮助!

【问题讨论】:

  • 我假设您在 filterPredicate 中的数据参数将是一个对象,因此您需要检查该对象的属性。 (例如 data.telefonnummer === 过滤器)
  • 你能把过滤器下拉的代码贴出来吗?

标签: angular typescript filter angular-material


【解决方案1】:

在这种情况下,按字符串过滤assignedunassigned 感觉不对。如果您的表格将获得更多列并且用户将能够设置 assignedunassigned 的值,那么您的敏感过滤将会出错。

但如果这不是问题(表有两列,一列仅用于数字),这里是您如何过滤它(虽然我没有看到您的数据源,但我根据列定义假设 status 是要检查的右键):

this.dataSource.filterPredicate = (data, filter): boolean => {
  const transformedFilter = filter.trim().toLowerCase();
  if (data.status.trim().toLowerCase() === transformedFilter) {
    return true;
  } else if (data.telefonnummer.trim().toLowerCase() === transformedFilter) {
    return true;
  };
  return false;
} 

简单的 sn-p 可以清楚地说明发生了什么。

附言如果telefonnummer 是数字而不是字符串,telefonnummer.trim() 可能会出错。 status.trim() 是否不是虚假值也值得检查

【讨论】:

    猜你喜欢
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-10
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    相关资源
    最近更新 更多