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

@astra1 here is some snippet from my code:

<!-- repeat this to all columns -->
 <ng-container cdkColumnDef="Column1">
         <mat-header-cell *cdkHeaderCellDef>
                 <!-- instead of adding mat-sort-header directive to the mat-header-cell, i've move it on span tag to separate sorting and filtering icon .-->
                <span mat-sort-header>Column1 </span>
                 <!-- i've applied css rules to the icon-->
                <span (click)="onFilterClick('col1')" class="filter-icon">
                    <mat-icon>keyboard_arrow_down</mat-icon>
                </span>
                <filter-template [openFilter]="true" *ngIf="templateFor === 'col1' "></filter-template>
         </mat-header-cell>
         <mat-cell *cdkCellDef="let row">{{row.Column1}}</mat-cell>
   </ng-container>
// mat-table component.ts
onFilterClick(templateFor:string){

  this.templateFor = templateFor;
}


// inside the filter-template component.ts 
@ViewChild('filterMenu') triggerMenu: MatMenuTrigger;
@Input() openFilter: boolean;

ngOnChanges(){

 if(this.openFilter) {
    this.triggerMenu.openMenu()
  }
}
<!-- filter-template component.html -->
<span #filterMenu="matMenuTrigger" [matMenuTriggerFor]="menu" id="filter-panel">

<mat-menu #menu="matMenu" [overlapTrigger]="false">
 <div (click)="$event.stopPropagation()" (keyup)="$event.stopPropagation()" (keydown)="$event.stopPropagation()">
   <form autocomplete="off"  (ngSubmit)="onFilterSubmit()" [formGroup]="filterForm">
			
    <mat-form-field  style="width: auto;">
	<mat-select formControlName="op" placeholder="Condition:">
		<mat-option *ngFor="let con of conditions" [value]="condi.id">
			 {{con.text}}
		</mat-option>
		</mat-select>
	</mat-form-field>
				
	<mat-form-field  *ngIf="!forFirstValue">
		<input formControlName="val1" matInput placeholder="Value">
	</mat-form-field>

	<mat-form-field class="font-sm" *ngIf="forSecondValue">
	   <input formControlName="val2" matInput placeholder="Second Value">
	</mat-form-field>
				
	<button [disabled]="hasNoValue" matRipple type="submit"></button>                
	</form>
  </div>
 </mat-menu>
</span>

I hope you'll get some clue from this snippet. 😆

@irowbin i required this feature, i have copied whole code but when i select value from select , it prevent selecting value due to event.stopPropagation(). I did not get any help Kindly help

Rashid75 avatar Sep 28 '18 12:09 Rashid75

@Rashid75 That was to prevent closing the matMenu while firing other events inside the matMenu. Maybe you just forgot to wrap with form group to get changed values of form control? e.g.


<div [formGroup]="filterForm"> <!-- i think you missed this line -->
    <input formControlName="filterValue" type="text" />
</div>

irowbin avatar Sep 28 '18 13:09 irowbin

@Rashid75 That was to prevent closing the matMenu while firing other events inside the matMenu. Maybe you just forgot to wrap with form group to get changed values of form control? e.g.

<div [formGroup]="filterForm"> <!-- i think you missed this block -->
    <input formControlName="filterValue" type="text" />
</div>

@irowbin I have wrapped it with formGroup but did not work, Any working code snippet ? I am stuck on it since last week

Rashid75 avatar Oct 01 '18 06:10 Rashid75

@Rashid75 here is a working example of just to test the values: https://stackblitz.com/edit/filter-columns?file=src%2Fapp%2Ffilter%2Ffilter-col.component.html Click on the button to open matManu, change some values and then click to the filter. You'll see the form data. Sorry for the ugly code. 😄

irowbin avatar Oct 02 '18 15:10 irowbin

Here working example. I was trying implement angular material chip on filter text when user press enter. Now I'm having issue. Can anyone help on this?

*First filter working good as expected *Second filter with material chip needs to be work same as filter 1 *Text turn to chip when press enter

samuelkavin avatar Oct 26 '18 08:10 samuelkavin

@samuelkavin That stackblitz link is 404 not found.

c0d3r1010 avatar Nov 07 '18 14:11 c0d3r1010

@irowbin would you mind sharing the code from the demo you posted? That is exactly what i need right now and im not getting it to work on my end.

Mkahnke avatar Nov 07 '18 15:11 Mkahnke

@samuelkavin can you post link again. Your stackblitz link isnt working.

sandgupta23 avatar Nov 17 '18 21:11 sandgupta23

I have answered about this topic and create a repo explain how I did it Filtering different columns in a material table

image

source 🛠,live preview 🚀

malbarmavi avatar Feb 22 '19 08:02 malbarmavi

I am trying to get this example to work with the code provided. However I'm getting an angular error on this line...

listings error

Is this a problem because the control is in a submenu? If so can I go about fixing this?

sbazinet avatar Jun 21 '19 20:06 sbazinet

angular_table_filtered Here is a link to the link to the stackblitz I used to develop my solution that you can browse in depth : Angular Material Filtered Table

Explanation on the thinking process:

I developped a solution for this problem using Mat Menu and Dynamic component injection. You will need a library named ng-dynamic-component to handle the inputs and the outputs of filters injected dynamically.

The main goal is to define the settings of the table through this structure type:

settingList = [
    { columnName: 'position', filterMode: FilterMode.NUMBER_MODE },
    { columnName: 'name', filterMode: FilterMode.TEXT_MODE },
    { columnName: 'weight', filterMode: FilterMode.NUMBER_MODE },
    { columnName: 'symbol', filterMode: FilterMode.TEXT_MODE },
    { columnName: 'date', filterMode: FilterMode.DATE_MODE },
  ];

It is the main reason why I inject my filter dynamically.

All filter follows this 'interface' to satisfy a common behaviour:

export class FilterImplementation {
  @Input() columnName: string;
  @Output() predicateEmitter = new EventEmitter<ColumnPredicate>();
}

The principle is to have a generic Mat Menu that returns a ColumnPredicate containing the name of the column to filter, and the predicate used to filter.

export class ColumnPredicate {
  name: string;
  predicate: (value:string) => boolean;
}

Next, you need to switch the filterPredicate based on the current filter triggered by the Mat Menu. It's a bit hacky for filtering, due to the unflexible behaviour of the table. I trigger the filter by passing a value that is not used in the filterPredicate logic.

  applyFilter(columnPredicate: ColumnPredicate) {
    const newPredicate = (data: PeriodicElement, notUsedParameter: string) => {
      return columnPredicate.predicate.call(undefined, data[columnPredicate.name]);
    }
    this.dataSource.filterPredicate = TableFilteredComponent.composePredicateAnd(this.dataSource.filterPredicate, newPredicate);
    this.dataSource.filter = 'useless trigger'; // Triggering filter (It is a little bit of hacking but hey, angular material not so flexible after all)
  }

  static composePredicateAnd(materialPredicate: (data, value) => boolean, filterPredicate: (data, value) => boolean) {
    return (data, value) => materialPredicate.call(undefined, data, value) && filterPredicate.call(undefined, data, value);
  }

To sum up the flow of this filter table: Trigger Mat Menu => Inject dynamically a filter component and giving it the name of the column => The filter returns a ColumnPredicate based on the information filled up => dataSource.filterPredicate is updated with the predicate and a fake value is sent to trigger the filter => Filtering is done

I would love to have a method on dataSource with the signature addFilter(column: string, predicate: (columnValue: string) => boolean) that would be for me the most natural way to define a column filter and avoid my hacky part.

Note that this is a prototype that I will continue to improve. Feel free to give your opinion about it and to point out any problem you have using it.

AxiomeCG avatar Jul 04 '19 16:07 AxiomeCG

Improved @alexisdoualle by allowing unlimited count of provided object keys and values and no need to know them by names: createFilter() { let filterFunction = function(data, filter) : boolean { let searchTerms = JSON.parse(filter); for (var property in searchTerms) { if (searchTerms.hasOwnProperty(property)) { if(data[property].toString().indexOf(searchTerms[property]) == -1) return false; } } return true; } return filterFunction; }

andzejsw avatar Jul 24 '19 11:07 andzejsw

@irowbin Can you please help me. I used your exact code even with the same dataSource but i am getting error as ERROR TypeError: filter.trim is not a function at MatTableDataSource._this.filterPredicate

in Function at line this.dataSource.filter = searchFilter; applyFilter() { let searchFilter: any = { values: this.searchValue, conditions: this.searchCondition, methods: this._filterMethods } console.log(this.dataSource); this.dataSource.filter = searchFilter; }

Can you plz plz help me

Rajesh5496 avatar Apr 07 '20 18:04 Rajesh5496

@Rajesh5496

// the datasource filter expect string instead of object here. 
this.dataSource.filter = searchFilter;

// change as 
this.dataSource.filter =  'term'; 

check this doc

irowbin avatar Apr 11 '20 03:04 irowbin

Closing since we do not expect to provide an example for this. If you are managing your own DataSource, handling multiple filters should be implemented by simply using your provided inputs to produce a new list of data to emit onto the observable connect stream. If you are using the MatTableDataSource to do this, you may find it challenging since that data source is meant more for a quick solution to avoid implementing your own data source, and it is not meant for complex situations like multi-input filters.

andrewseguin avatar May 26 '21 19:05 andrewseguin

This issue has been automatically locked due to inactivity. Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

This action has been performed automatically by a bot.