2
votes

Since my column names and corresponding data is populated within ngFor, how can I pass a separate filter row that filters data for each column in angular material table?

The filter row should be below the header row that shows the various column names.

1

1 Answers

0
votes

If you want to use filter only specific columns you need to override filterPredicate like so

import {MatTableDataSource} from '@angular/material';

export interface Element {
      id: string;
      name: number;
      age:number;
}
const yourDataArray: Element[] = [
      {id: 1, name: 'Ali', age:23},
      {id: 2, name: 'Umar', age:43},
      {id: 3, name: 'Asim', age:21},
      ]
export class TableFiltering{
dataSource = new MatTableDataSource(yourDataArray);

ngOnInit() {
this.dataSource.filterPredicate = (data: Element, filter:string) =>
      (data.name.indexOf(filter) !== -1 ||
        data.id.indexOf(filter) !== -1 );
  }
.
.
.
.
}

Or apply filter to all columns by assigning a value to filter


ngOnInit() {
// Call applyFilter function with a filter value from code or template
   applyFilter(filterValue: string) {
    // filterValue = filterValue.trim(); // Remove whitespace
    // filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
    this.dataSource.filter = filterValue;
  }
}

Use any one of the two(filterPredicate or dataSource.filter) as per your requirements. But do remember to use them in ngOnInit().

Using MatTableDataSource is useful as per the official docs.