Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material Table filterPredicate

I'm trying to filter a set of data by a specific object key Ex: I have a set of skills, I want to see all of the skills at level 2.

I have read through the docs, this GitHub example, and this other question but I can't find an actual example of how user input can be used to filter by an object key. So far nothing happens when a user clicks on a skill level.

Right now my HTML looks like:

<mat-button-toggle-group #group="matButtonToggleGroup"
    class="margin-1" (change)=toggleSkillLevel(group.value)>

  <mat-button-toggle value="0">
    0
  </mat-button-toggle>

  <mat-button-toggle value="1">
    1
  </mat-button-toggle>

  <mat-button-toggle value="2">
    2
  </mat-button-toggle>

  <mat-button-toggle value="all">
    ALL
  </mat-button-toggle>

</mat-button-toggle-group>

{{ dataSource.filteredData }}

and my TS looks like:

 import { Skill, SKILL_DATA } from '../data/skills-details';

...
...

  toggleSkillLevel(level){
    console.log('Only show level ' + level + ' skills...');
    this.dataSource.filterPredicate =
            (data: Skill, filter: string) => data.level == level;
  }
like image 949
av0000 Avatar asked Jan 26 '18 21:01

av0000


People also ask

What is filterPredicate in angular?

By setting the filterPredicate , you only define how a filter value should be applied on your data when a filter value is given. It's only the definition of the filter function, you do not actually apply the filter with it. Hence, you only need to define this once, which could for example happen in the ngOnInit .

What is * MatHeaderCellDef?

MatHeaderCellDef extends CdkHeaderCellDefHeader cell definition for the mat-table. Captures the template of a column's header cell and as well as cell-specific properties. Selector: [matHeaderCellDef]


1 Answers

By setting the filterPredicate, you only define how a filter value should be applied on your data when a filter value is given. It's only the definition of the filter function, you do not actually apply the filter with it. Hence, you only need to define this once, which could for example happen in the ngOnInit.

ngOnInit() {
  this.dataSource.filterPredicate =
      (data: Skill, filter: string) => !filter || data.level == filter;
}

To then apply your filter with an actual value, you need to set dataSource.filter, for example:

toggleSkillLevel(level) {
  this.dataSource.filter = level;
}
like image 107
Kim Kern Avatar answered Oct 14 '22 15:10

Kim Kern