4

I've been looking for any examples of a filter on a column in mat table and so far haven't found any.I did came some bits and pieces information about filterPredicate method but did not get exactly as to how approach it.

My need is that an individual column should have a filter like a text-box or a checkbox based on which the dataSource will be filtered.

Stackblitz

kal93
  • 522
  • 1
  • 9
  • 22

1 Answers1

5
displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
dataSource = new MatTableDataSource(ELEMENT_DATA);

applyFilter(filterValue: string) {
this.dataSource.filter = filterValue.trim().toLowerCase();
this.dataSource.filterPredicate = (data: Element, filter: string) => 
data.name.toLowerCase().indexOf(filter) != -1;
}

export interface Element {
name: string;
position: number;
weight: number;
symbol: string;
}

const ELEMENT_DATA: Element[] = [
{position: 1, name: 'hydrogen', weight: 1.0079, symbol: 'Hi up'},
{position: 2, name: 'Helium', weight: 4.0026, symbol: 'Hi upp'},
{position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
{position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
{position: 5, name: 'Boron', weight: 10.811, symbol: 'B'},
{position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'},
{position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N'},
{position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
{position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
{position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
];

// html

 <mat-form-field>
  <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
</mat-form-field>

I have filtered only name field. In this way you can filter in any column

monir tuhin
  • 441
  • 3
  • 13
  • 27
  • Can this work on a particular column?I know this works as kind of table level filter.What I'm looking for is something like ag-grid which has a filter icon on the column which contains a dropdown or a textbox. – kal93 Jun 29 '18 at 12:28
  • this does work with when you're filtering on column that have string type for cell values.In case of number it lags behind by 1 keystroke.Updated the question with stackblitz. – kal93 Jul 10 '18 at 18:47
  • Hi @kal93 I used the same concept but I am using the menus and submenus to filter out the table but the problem is I dont want to make seperate filter methods can you guide me how can I make only one method the hint is where in the code monir tuhin used name I want to use the properties dynamically so will pass the string properties of the class from html file so how to typecast in ts file just want to get the hint like how can we achieve that? – kushal Baldev Jul 18 '20 at 15:02