过滤角度过滤的Angular Material Table中的特定列?

13 angular-material2 angular

我正在使用 mat-table.它有一个工作正常的过滤器.

针对以下数据进行过滤(所有列)

const ELEMENT_DATA: Element[] = [
  {position: 14598, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
  {position: 24220, name: 'Helium', weight: 4.0026, symbol: 'He'},
  {position: 39635, name: 'Lithium', weight: 6.941, symbol: 'Li'},
  {position: 42027, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
  {position: 53216, name: 'Boron', weight: 10.811, symbol: 'B'},
  {position: 60987, name: 'Carbon', weight: 12.0107, symbol: 'C'},
  {position: 70976, name: 'Nitrogen', weight: 14.0067, symbol: 'N'},
  {position: 81297, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
  {position: 90975, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
  {position: 18879, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
  {position: 11209, name: 'Sodium', weight: 22.9897, symbol: 'Na'}

];
Run Code Online (Sandbox Code Playgroud)

但是现在我正在尝试更改过滤器,因为我想要的是过滤器仅用于"位置","名称","符号"列.我通过这个例子,但是在角度5中过滤Angular Material表中的特定列.我不明白请帮帮我

mycode的

bug*_*ugs 24

您必须覆盖filterPredicatedataSource.

以下是如何操作的示例:工作演示


实际上,您希望指定过滤器应用于数据的属性:

this.dataSource.filterPredicate = function(data, filter: string): boolean {
    return data.name.toLowerCase().includes(filter) || data.symbol.toLowerCase().includes(filter) || data.position.toString().includes(filter);
};
Run Code Online (Sandbox Code Playgroud)


Cod*_*Spy 5

Angular Material Tables中,我们可以从数据本身创建基于列的过滤器。

来源链接

演示链接

在此输入图像描述

为此,我们需要使用customFilter()方法重写filterPredicate方法

        ...
        ngOnInit() {
            this.getRemoteData();

            // Overrride default filter behaviour of Material Datatable
            this.dataSource.filterPredicate = this.createFilter();
        }
        ...

        // Custom filter method fot Angular Material Datatable
        createFilter() {
            let filterFunction = function (data: any, filter: string): boolean {
            let searchTerms = JSON.parse(filter);
            let isFilterSet = false;
            for (const col in searchTerms) {
                if (searchTerms[col].toString() !== '') {
                isFilterSet = true;
                } else {
                delete searchTerms[col];
                }
            }

            let nameSearch = () => {
                let found = false;
                if (isFilterSet) {
                for (const col in searchTerms) {
                    searchTerms[col].trim().toLowerCase().split(' ').forEach(word => {
                    if (data[col].toString().toLowerCase().indexOf(word) != -1 && isFilterSet) {
                        found = true
                    }
                    });
                }
                return found
                } else {
                return true;
                }
            }
            return nameSearch()
            }
            return filterFunction
        }
Run Code Online (Sandbox Code Playgroud)

在这里检查完整的工作代码