1

I'm using a dataSource to store all my data. Until now, I was using the standard filter when performing a search. However, now I would like to perform searchs with the "OR" operator.

Example :

{name : john, age : 25, work : driver}

{name : peter, age : 28, work : writer}

{name : james, age : 39, work : athlete}

If I input "john james" I want the filter function to get me line 1 AND line 3.

I'm pretty sure we have to use a filterPredicate, but I really don't understand how to create/use those, and I couldn't find any decent/working example

The documentation would not help much besides giving me a protoype :

filterPredicate: ((data: T, filter: string) => boolean);

Do you guys have any idea or code example how to achieve that ?

Here is what my function looks like for now for a basic search :

  applyFilter(filterValue: string) {
    filterValue = filterValue.toLowerCase();
    this.dataSource.filter = filterValue;
  }
Zako
  • 151
  • 2
  • 11
  • Possible duplicate of [How to apply filters to \*ngFor?](https://stackoverflow.com/questions/34164413/how-to-apply-filters-to-ngfor) – Dalorzo Oct 04 '19 at 12:35
  • Definitely not, I'm trying to modify the default filtering method of a dataSource so that all my future searchs perform the way I want them to. – Zako Oct 04 '19 at 12:55

1 Answers1

1
const users = [
  {name : 'john', age : 25, work : 'driver'},
  {name : 'peter', age : 28, work : 'writer'},
  {name : 'james', age : 39, work : 'athlete'}
]

const query = "john james";

const filtered = users.filter(e => query.includes(e.name));

This should work :)

using DataSource:

this.dataSource.filterPredicate = (data, filter) => filter.includes(data.name)
Maciej Wojcik
  • 2,115
  • 2
  • 28
  • 47
  • Hello, I can't seem to apply your predicate to a dataSource. `this.dataSource.filter(e => filterValue.includes(e.name));` doesnt compile – Zako Oct 04 '19 at 12:50
  • 'this.dataSource.filterPredicate = (data, filter) => filter.includes(data.name);' – Maciej Wojcik Oct 04 '19 at 12:58
  • I found what was wrong, need to pass `this.dataSource.data`. Seems to be working now : `this.dataSource.filterPredicate = (data=this.dataSource.data, filter : string) => filter.includes(data.name)` Thank you, your answer helped. – Zako Oct 04 '19 at 15:56