components icon indicating copy to clipboard operation
components copied to clipboard

[Table] - Add example with multiple filtering columns

Open dev054 opened this issue 9 years ago • 56 comments

Bug, feature request, or proposal:

Proposal.

What is the expected behavior?

It would be good to see an example showing multiple filters (in this case inputs/selects) to filter rows/cells in md-table.

You can see this as an example.

What is the current behavior?

Currently the filter example just shows how to filter multiple columns by a single input.

dev054 avatar Jul 31 '17 21:07 dev054

@patrickschlaepfer I think i have no idea of your exception! 🤣

irowbin avatar Mar 08 '18 14:03 irowbin

@irowbin I also get cannot read property of 'templateRef' of undefined. From what I can tell the html bit <filter-template [openFilter]="true" ... needs to have some sort of templateRef passed to it

pjcoupe avatar Mar 12 '18 18:03 pjcoupe

didn't try but i think typo is here <filter-template [openFilter]="true" *ngIf="templateFor === 'col1">

missing single quote in col1

erickyi2006 avatar Mar 13 '18 00:03 erickyi2006

@patrickschlaepfer @erickyi2006 Maybe there is some typo i guess. 😆

<filter-template [openFilter]="true"    *ngIf=" templateFor === 'col1' "></filter-template> 

irowbin avatar Mar 13 '18 02:03 irowbin

I used a different approach; since MatTableDataSource.filter only accepts a string as an argument, I created a custom filterPredicate where each input passes an object that has been stringified.

With two form controls like this in the template:

    <mat-form-field>
      <input matInput [formControl]="idFilter" placeholder="id">
    </mat-form-field>

    <mat-form-field>
      <input matInput [formControl]="nameFilter" placeholder="name">
    </mat-form-field>

I subscribed to value changes in the ts:


    private idFilter = new FormControl();
    private nameFilter = new FormControl();
    private filterValues = {id: '', name: ''}

    this.idFilter.valueChanges
    .subscribe(value => {
      this.filterValues['id'] = value;
      this.dataSource.filter = JSON.stringify(this.filterValues)
    })
    this.nameFilter.valueChanges
    .subscribe(value => {
      this.filterValues['name'] = value
      this.dataSource.filter = JSON.stringify(this.filterValues)
    })

    // custom filterPredicate function: 
    this.dataSource.filterPredicate = this.createFilter();

    createFilter() {
        let filterFunction = function(data, filter) : boolean {
          let searchTerms = JSON.parse(filter)
          return data.id.toString().indexOf(searchTerms.id) != -1 
              && data.name.indexOf(searchTerms.name) != -1
        }
        return filterFunction
    }

alexisdoualle avatar Mar 27 '18 08:03 alexisdoualle

@alexisdoualle it's work for me. Tks <3

Tronghoang avatar Apr 08 '18 17:04 Tronghoang

@alexisdoualle Where are the values for data and filter in function createFilter( ), do they get auto assigned or do we have to pass some value to them ?

No proper documention for using filterPredicate in the Angular Material, so having a hard time understanding how it actually works

SushanRajShakya avatar Apr 17 '18 07:04 SushanRajShakya

@drop039beats Yes they are auto assigned, you don't have to worry about them. By creating your own predicate function, you're overriding the default filter function, which only checks for the presence of string "filter" in the available data (MatTableDataSource). With a custom function you can specify which field you want to check (as in data.id), and with my workaround you can assign each input to every field in the table.

You can create a MatTableDataSource object simply like this:

      this.dataSource = new MatTableDataSource()
      this.dataSource.filterPredicate = this.createFilter();
      this.dataSource.data = yourData

alexisdoualle avatar Apr 17 '18 09:04 alexisdoualle

@alexisdoualle Thanks a lot it worked like charm, we need to set filterPredicate before we set the dataSource.filter that is why it was not working for me. Better to put it in onNgInit( )

I had to make the filterPredicate dynamic based on the number of columns to be filtered

public createFilter(): (data: any, filter: any) => boolean {
    const filterFunction = function(data, filter): boolean {
      const searchData = JSON.parse(filter);
      let status = false;
      for (const key in searchData) {
        if (data[key].indexOf(searchData[key]) !== -1) {
          status = true;
        } else {
          status = false;
          break;
        }
      }
      return status;
    };
    return filterFunction;
  }

SushanRajShakya avatar Apr 17 '18 09:04 SushanRajShakya

@alexisdoualle With your implementation are you able to search two terms within the same column? I did something similar with a custom predicate but I wasn't able to do something like search for 'John' and 'Bob' in the name filter at the same time.

srukali avatar Apr 26 '18 19:04 srukali

@srukali Sure, if you want to have only one filter for names and be able to search multiple names separated by, say, a white space, you could do something like this:

createFilter() {
   let filterFunction = function(data: any, filter: string) : boolean {
     let searchTerms = JSON.parse(filter)
     let idSearch = data.id.toString().indexOf(searchTerms.id) != -1 
     let nameSearch = () => {
       let found = false;
       searchTerms.name.trim().toLowerCase().split(' ').forEach(word => {
         if (data.name.toLowerCase().indexOf(word) != -1) {found = true}
       });
       return found
     }
     return idSearch && nameSearch()
   }
   return filterFunction
 }

alexisdoualle avatar Apr 26 '18 20:04 alexisdoualle

@alexisdoualle, I use your createFilter function. If I have two arguments (like name and id), all works fine. But if I return third value, data is not displayed

NikolaiGarkusha avatar Apr 27 '18 13:04 NikolaiGarkusha

@irowbin any chance we can get a stackblitz for the gif you shared?

kal93 avatar Jun 17 '18 10:06 kal93

stackblitz would be great!

p97z avatar Jun 19 '18 11:06 p97z

Building on-top of what @alexisdoualle has given for a per-column filtering solution I would like to add in how I managed to fit my filter inputs inside of my table column headers instead of else-where on the page. Also not have them trigger column sorting when they are focused for input.

I'd like to preface with saying this is just a proof of concept and small snippet, I hope it helps though!

<ng-container *ngFor="let column of displayedColumns" matColumnDef="{{column}}">
  <mat-header-cell *matHeaderCellDef>
    <span mat-sort-header>{{column | uppercase}}</span>
    <input class="filter-input" matInput (keyup)="applyFilter(column, $event.target.value)" placeholder="Filter {{column}}" />
  </mat-header-cell>
  <mat-cell *matCellDef="let row"> {{row[column]}}</mat-cell>
</ng-container>

If you are NOT using mat-sort functionality then the trick is simple, just include your filter input inside of the mat-header-cell. If you are using mat-sort functionality then you will need to instead put your column heading text inside of a span and give that span the mat-sort-header class instead of the mat-header-cell.

Sample result: image

KMathisGit avatar Jun 29 '18 14:06 KMathisGit

Is it possible to have it both ways? I mean filtering on the full table and per column? I don't see how to do it after modifying the filterPredicate. Anyone?

jordanA29 avatar Jul 10 '18 13:07 jordanA29

@alexisdoualle 's solution worked for me.But I still can't figure out a way to retain the default filter once filterPredicate is overriden. StackBlitz I'm for a way to filter on top of whatever data the column filters return. Is this even possible after overriding filterPredicate

kal93 avatar Aug 24 '18 15:08 kal93

@kal93 @jordanA29 https://stackblitz.com/edit/angular-hbakxo-xctfqy?file=app/table-filtering-example.ts

This lets you have individual filters for each column and a top-level filter for all columns (which you can test with the value '999')

The trick was adding a property to the stringified object (.topFilter), which when set to true (by the top-level form control) will make the custom predicate function use the OR operator, so that every field is parsed, like in the default predicate.

  customFilterPredicate() {
    const myFilterPredicate = function(data:PeriodicElement, filter:string) :boolean {
      let searchString = JSON.parse(filter);
      let nameFound = data.name.toString().trim().toLowerCase().indexOf(searchString.name.toLowerCase()) !== -1
      let positionFound = data.position.toString().trim().indexOf(searchString.position) !== -1
      if (searchString.topFilter) {
          return nameFound || positionFound 
      } else {
          return nameFound && positionFound 
      }
    }
    return myFilterPredicate;
  }

Of course, if you want all columns to be parsed (like 'weight' and 'symbol'), you need to add them to the code, either explicitly, or by looping through the 'data' parameter's properties.

alexisdoualle avatar Aug 25 '18 22:08 alexisdoualle

data.name.toString().trim().toLowerCase().indexOf(searchString.name.toLowerCase()) !== -1

Hey Do you have any example how we can achieve same functionality of filter on each column using dynamic data? Thank you

shemanifisher avatar Sep 12 '18 11:09 shemanifisher

@kal93 @jordanA29 https://stackblitz.com/edit/angular-hbakxo-xctfqy?file=app/table-filtering-example.ts

This lets you have individual filters for each column and a top-level filter for all columns (which you can test with the value '999')

The trick was adding a property to the stringified object (.topFilter), which when set to true (by the top-level form control) will make the custom predicate function use the OR operator, so that every field is parsed, like in the default predicate.

  customFilterPredicate() {
    const myFilterPredicate = function(data:PeriodicElement, filter:string) :boolean {
      let searchString = JSON.parse(filter);
      let nameFound = data.name.toString().trim().toLowerCase().indexOf(searchString.name.toLowerCase()) !== -1
      let positionFound = data.position.toString().trim().indexOf(searchString.position) !== -1
      if (searchString.topFilter) {
          return nameFound || positionFound 
      } else {
          return nameFound && positionFound 
      }
    }
    return myFilterPredicate;
  }

Of course, if you want all columns to be parsed (like 'weight' and 'symbol'), you need to add them to the code, either explicitly, or by looping through the 'data' parameter's properties.

Hey Do you have any example how we can achieve same functionality of filter on each column using dynamic data? Thank you

shemanifisher avatar Sep 12 '18 11:09 shemanifisher