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

前端 未结 4 867
温柔的废话
温柔的废话 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:26

    Adding to bugs' answer. Here's a more elaborate implementation,

    export class FilterTable implements AfterViewInit {
      //some datasource
      datasource //=
      displayedColumns //=insert column names on which you want to filter whether they are displayed or not, but present in the datasource
    
      // Apply filter to the datasource
      applyFilter(filterValue: string) {
        this.datasource.filter = filterValue;
      }
    
    
      ngAfterViewInit() {
        // Overwriting filterPredicate here, as it needs to be done after the datasource is loaded.
        this.datasource.filterPredicate = (data, filter) => {
          var tot = false;
          for (let column of this.displayedColumns) {
            //incase if there is a date type and is displayed differently using a pipe, then convert it intorequired format before filtering
            //check if all the columnson which you are filtering are actually present
            if ((column in data) && (new Date(data[column].toString()).toString() == "Invalid Date")) {
              //if not date column
              tot = (tot || data[column].toString().trim().toLowerCase().indexOf(filter.trim().toLowerCase()) !== -1);
            } else {
              //change this to the format in which date is displayed
              var date = new Date(data[column].toString());
              var m = date.toDateString().slice(4, 7) + " " + date.getDate() + " " + date.getFullYear();
              tot = (tot || m.toLowerCase().indexOf(filter.trim().toLowerCase()) !== -1);
            }
          }
          return tot;
        }
      }
    }
    

    Please feel free to suggest edits, if this could be improved

提交回复
热议问题