Reputation: 106
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();
}
Upvotes: 0
Views: 4156
Reputation: 3661
My approach would be to use the filterPredicate
and filter
property, and then coalesce (i.e. use the ??
and ''
) the data/values so that undefined becomes the empty string you need to compare. For example:
// config filter via some form control:
this.filterInputFormControl.valueChanges.subscribe((searchString) => {
this.filteredValues['col_A'] = searchString;
this.filteredValues['col_B'] = searchString;
this.dataSource.filter = JSON.stringify(this.filteredValues);
});
// filter predicate:
this.dataSource.filterPredicate = (data: any, filter: string): boolean => {
const searchString = JSON.parse(filter);
return (
(data.col_B ?? '').toString().trim().toLowerCase().indexOf(searchString.col_B.toLowerCase()) !== -1 ||
(data.col_A ?? '').toString().trim().toLowerCase().indexOf(searchString.col_A.toLowerCase()) !== -1
);
};
Upvotes: 0
Reputation: 106
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.
Upvotes: 1
Reputation: 196
I guess that you are looking for that:
applyFilter(filterValue: string) {
if (!!filterValue) {
this.dataSource.filter = filterValue.trim().toLowerCase();
}
}
Upvotes: 0