Search code examples
angularangular-material2angular-material-table

How to exclude undefined and null when use filter in Angular Material Table?


please help. Is there any way I can exclude the undefined and null from filtering? So, if the cell value is null or undefined it's not being shown when the user types "null" or "undefined" in search input.

Incoming table data:

dataSource: MatTableDataSource

The below method is applied on input:

  applyFilter(filterValue: string) {
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }

Solution

  • I found the answer, in case anybody is looking for it.

      applyFilter(filterValue: string) {
        this.dataSource.data.forEach(element => {
          for (const key in element) {
            if (!element[key] || element[key] === null) {
              element[key] = '';
            }
          }
        });
        this.dataSource.filter = filterValue.trim().toLowerCase();
      }
    

    applyFilter() function is added to input, and it takes input value as argument. On filtering you need to check the incoming data array of objects (it will be your rows in Material Table), and for each object property check if it is null or undefined. If yes - assign empty string. This empty string will be then concatinated together with other values by material for filtering.