Reputation: 61
Im trying to add a filter to my table.
Here is the live demo of the table with the filter. However, the filters do not narrow down. For example if I apply the ID filter of 3 and status of active. It should only display 1 results as there is only 1 user with ID of 1 and status of Active. Instead, it will display all the users with ID of 3 and also all all the users with status of active.
Is there are modifications I can do to this createFilter to output the desired result?
// Custom filter method fot Angular Material Datatable
createFilter() {
let filterFunction = function (data: any, filter: string): boolean {
let searchTerms = JSON.parse(filter);
let isFilterSet = false;
for (const col in searchTerms) {
if (searchTerms[col].toString() !== '') {
isFilterSet = true;
} else {
delete searchTerms[col];
}
}
console.log(searchTerms);
let nameSearch = () => {
let found = false;
if (isFilterSet) {
for (const col in searchTerms) {
searchTerms[col].trim().toLowerCase().split(' ').forEach(word => {
if (data[col].toString().toLowerCase().indexOf(word) != -1 && isFilterSet) {
found = true
}
});
}
return found
} else {
return true;
}
}
return nameSearch()
}
return filterFunction
}
Here is the tutorial I followed and the source code.
Upvotes: 0
Views: 431
Reputation: 4184
found
will be true when one of searchTerms
matches. If you want to return true only when all the searchTerms
match, you should do like this.
if (isFilterSet) {
for (const col in searchTerms) {
if (searchTerms[col].toString() === '') {
continue;
} else {
let found = false;
searchTerms[col].trim().toLowerCase().split(' ').forEach(word => {
if (data[col].toString().toLowerCase().indexOf(word) != -1 && isFilterSet) {
found = true
}
});
if (!found) {
return false;
}
}
}
return true;
} else {
return true;
}
Upvotes: 1