How to filter in more than one column in ng2 table?

I am using the ng2-table component: https://github.com/valor-software/ng2-table , but I need to add a filter for each column.

In my code, I have filtering in the: name column, but I want to add a filter for the code too.

public columns:Array<any> = [ {title: 'Code', name: 'code',sort: 'asc'}, {title: 'Name', name: 'name', sort: 'asc'} ]; public page:number = 1; public itemsPerPage:number = 1; public maxSize:number = 5; public numPages:number = 1; public length:number = 0; public config:any = { paging: true, sorting: {columns: this.columns}, filtering: {filterString: '', columnName:'name'} }; 

How to add another filter?

I really appreciate if someone can give me an example.

+6
source share
1 answer

First of all, you need to create a configuration for the fields that you want to filter. I am going to use the example given at http://valor-software.com/ng2-table/ as a base. Therefore, in your .ts component, you would:

 public config: any = { sorting: { columns: this.columns }, filtering: { position: { filterString: '' }, office: { filterString: '' } } }; 

Each column for filtering will save the specified row in the filterString field. Here columnName not needed, as I hardcode it. Then in the html create the inputs, one per filter:

 <input placeholder="Position" [ngTableFiltering]="config.filtering.position" (tableChanged)="onChangeTable(config)"/> <input placeholder="Office" [ngTableFiltering]="config.filtering.office" (tableChanged)="onChangeTable(config)"/> <ng-table [config]="config.sorting" (tableChanged)="onChangeTable(config)" [rows]="rows" [columns]="columns"> </ng-table> 

And finally, the real data filter (again in the component.ts file):

 public changeFilter(data: any, config: any): any { return data.filter((item: any) => item["position"].match(this.config.filtering.position.filterString) && item["office"].match(this.config.filtering.office.filterString)); } 

Note that I use the AND logic here to filter, you may want to OR'ing them.

+5
source

All Articles