Filtering specific column in Angular Material Table with filtering in angular?

前端 未结 4 869
温柔的废话
温柔的废话 2021-02-19 00:44

I am using mat-table. It has a filter which works fine.

Filter happened against this below data (All columns)

const ELEMENT_DATA: Element[] = [
  {posit         


        
4条回答
  •  伪装坚强ぢ
    2021-02-19 01:22

    In Angular Material Tables, we can create column based filters from data itself.

    Source Link

    Demo Link

    For that, we need to override the filterPredicate method with customFilter() method

            ...
            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
            }
    

    Check complete working code here

提交回复
热议问题