How to add column wise filters in mat data table in angular 5

Issue

How to add custom filters to columns for mat data table by using angular 5 and
angular material

Solution

below is the html markup

<div class="modal-body">
  <div >
      <mat-form-field>
        <input
          matInput
          type='text'
          placeholder='Type to filter the name column...'
          (keyup)='updateFilter($event)'
        />
      </mat-form-field>

      <ngx-datatable
        style="cursor: pointer;"
        #table
        class='material'
        [columns]="columns"
        [columnMode]="'force'"
        [headerHeight]="50"
        [footerHeight]="50"
        [rowHeight]="'auto'"
        [limit]="10"
        [rows]='rows'
        [selectionType]="'single'"
        (select)="onSelect($event)">
      </ngx-datatable>
  </div>

</div>

<div class="modal-footer">
  <button type="button" class="btn btn-default" (click)="bsModalRef.hide()">{{closeBtnName}}</button>
</div>

you can use the following method to filter n number of rows

updateFilter(event) {
    const val = event.target.value;

    /* filter our data */
    const temp = this.temp.filter((d) => {

       var isTrue = false;

       for( var i = 0; i < this.columns.length; i++){
          var name = this.columns[i].name;
          if(d[name] != null)
             isTrue = d[name].toString().toLowerCase().indexOf(val.toLowerCase()) !== -1 || !val;
             if(isTrue)
                break;
       }  
       return isTrue;   
    });

  // update the rows
  this.rows = temp;
}

Answered By – Ambreen Haleem

Answer Checked By – Mildred Charles (AngularFixing Admin)

Leave a Reply

Your email address will not be published.