Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Individual Column filter for mat table

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

like image 1000
kal93 Avatar asked Nov 01 '25 03:11

kal93


1 Answers

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

like image 166
monir tuhin Avatar answered Nov 02 '25 20:11

monir tuhin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!