带有嵌套对象的 Angular Material 2 DataSource 过滤器 [英] Angular Material 2 DataSource filter with nested object

查看:25
本文介绍了带有嵌套对象的 Angular Material 2 DataSource 过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有材质 2 的 angular 4 项目,我想过滤 MatTable 中的数据.当我们在未嵌套的字段上过滤数据时,DataSource 过滤器工作正常.

I have angular 4 project with material 2, I want to filter the data in MatTable. DataSource filter is working fine when we filter data on field which are not nested.

this.dataSource = new MatTableDataSource([
     { orderNumber: 1, orderInfo: { type: 'ABC'}, date: '12/3/2012 9:42:39 AM'},
     { orderNumber: 3, orderInfo: { type: 'Hello' }, date: '12/2/2018 9:42:39 AM'},
]);

过滤器对于 orderNumber、date 工作正常,但对于 orderInfo 对象中的 type 字段无法正常工作.

Filter is working fine for orderNumber, date but not working properly with type field in orderInfo object.

推荐答案

DataSource 有 filterPredicate() 方法需要在我们的应用程序中重写如下.数据源初始化后,将此代码添加到您的组件中.

DataSource has filterPredicate() method that needs to override in our application as follows. Add this code in your component after data source initialization.

this.dataSource.filterPredicate = (data, filter: string)  => {
  const accumulator = (currentTerm, key) => {
    return key === 'orderInfo' ? currentTerm + data.orderInfo.type : currentTerm + data[key];
  };
  const dataStr = Object.keys(data).reduce(accumulator, '').toLowerCase();
  // Transform the filter by converting it to lowercase and removing whitespace.
  const transformedFilter = filter.trim().toLowerCase();
  return dataStr.indexOf(transformedFilter) !== -1;
};

这篇关于带有嵌套对象的 Angular Material 2 DataSource 过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆