To filter specific columns only, it is necessary to customize the filterPredicate in the following way:
import {MatTableDataSource} from '@angular/material';
export interface Element {
id: string;
name: number;
age:number;
}
const dataItemsArray: 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(dataItemsArray);
ngOnInit() {
this.dataSource.filterPredicate = (data: Element, filter:string) =>
(data.name.indexOf(filter) !== -1 ||
data.id.indexOf(filter) !== -1 );
}
.
.
.
.
}
Alternatively, for filtering all columns, set a value to the filter property:
ngOnInit() {
// To apply filter, call the applyFilter function with a filter value from code or template
applyFilter(filterValue: string) {
// Remove white spaces and convert to lowercase
// filterValue = filterValue.trim();
// filterValue = filterValue.toLowerCase();
this.dataSource.filter = filterValue;
}
}
You can choose either approach (filterPredicate or dataSource.filter) based on your needs. Ensure that you implement them within ngOnInit().
Using MatTableDataSource as suggested in the official documentation.