Implementing column specific filters on dynamically created angular material data table

Viewed 324

I am generating a material data table dynamically with data as well as displayedColumns coming from backend.

.html:

      <mat-form-field appearance="standard">
        <mat-label>Filter</mat-label>
        <input matInput (keyup)="applyFilter($event)" placeholder="Ex. Mia" #input>
      </mat-form-field>
      <div class="mat-elevation-z8">
        <table mat-table [dataSource]="dataSource" matSort>     
          <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
          <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
          <ng-container *ngFor="let column of displayedColumns">
            <ng-container [matColumnDef]="column">
              <th mat-header-cell *matHeaderCellDef >   {{ column }}  </th>
              <td mat-cell *matCellDef="let row">{{row[column]}}</td>
            </ng-container>
          </ng-container>
        </table>      
        <mat-paginator [pageSizeOptions]="[10, 5, 25, 100]" aria-label="Select page of users"></mat-paginator>
      </div>  

If it was not a dynamic table, I can add an input field in html for column filters and write code in .ts to use filterPredicate property to customize the logic for column specific filtering.

.ts code excerpts:

....
 this.dataSource.filterPredicate = this.createFilter();
...
...
createFilter(): (data: any, filter: string) => boolean {
    let filterFunction = function(data, filter): boolean {
       let searchTerms = JSON.parse(filter);
       let descr:string = data.description??"";       
       return (data.view_name.toLowerCase().indexOf(searchTerms.view_name) !== -1)
         && (descr.toString().toLowerCase().indexOf(searchTerms.description) !== -1);  

However, the table being dynamic I have 2 questions:

  1. if I add column filter in html, how do I identify for which column user entered text inside .ts?
  2. Even if I identify the column name and say I got it into a variable, how do I write the filtering logic that is equivalent to above since I can't refer to searchTerms.view_name directly?
0 Answers
Related