Luke
Luke

Reputation: 181

Angular Material Table filterPredicate to filter objects

I have a mat-table with a text input to filter it's results.

Datasource is:

[
    {
        "articolo": {
            "code": "22.398.14",
            "url": "/url1"
        },
        "color": "white",
        "weight": "10"
    },
    {
        "articolo": {
            "code": "22.398.15",
            "url": "/url2"
        },
        "color": "red",
        "weight": "20"
    }
]

I add this in html:

    <mat-form-field>
    <mat-label>Filtra</mat-label>
    <input matInput (focus)="setupFilter('articolo')" (keyup)="applyFilter($event)" placeholder="Filter">
    </mat-form-field>

And in ts:

setupFilter(column: string) {
    this.data.filterPredicate = (data, filter) => {
      data[column].code.indexOf(filter) != -1;
    }
  }

applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.data.filter = filterValue.trim().toLowerCase();
  }

But nothing happens

If I add a console.log inside filterPredicate it doesn't fire:

this.data.filterPredicate = (data, filter) => {
      console.log(data);
...

What's wrong?

thanks

Upvotes: 4

Views: 9731

Answers (2)

Qarun
Qarun

Reputation: 74

If you need to make own filtering behaviour for your "code" attribute create it onese in constructor or ngOnInit hook, just like this:

ngOnInit() {
    this.dataSource = new MatTableDataSource(this.data);
    this.dataSource.filterPredicate = (data, filter) => {
      return data.articolo.code.indexOf(filter) != -1;
    }
  }

Pay attention on return statement in filterPredicate. You don't used it! Also, you don't need this (focus)="setupFilter('articolo')" . all you have to do just call applyFilter, as you do it, like this:

applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();
    console.log(this.dataSource.filteredData);
  }

Then you can see in console your filtered data during changing input value. Hope, I helped you .I can't understand why your data is nested. Good idea weel be first convert this data, then apply filters. May be in your case it's good.

Upvotes: 1

A-Figerou
A-Figerou

Reputation: 165

You are assigning a function nevertheless not calling it.

this.data.filterPredicate = (data, filter) => { data[column].code.indexOf(filter) != -1; }

Try

to console log this.data.filterPredicate(data, filter). This will return nothing, arrgggh you have a function that is not returning anything.

Catch (e) =>

do one thing at a time: so, a function. Console log direct.

Upvotes: 0

Related Questions