Search code examples
angulartypescriptangular-material-table

Reset Angular's Mat Data Table search filter


My web app uses a Material Data Tale (https://code-maze.com/angular-material-table/) to display some existing data. It also has various filters including the Mat Data Table's built in search filter. My problem is I can reset all of my other self-implemented filters on a 'clear all filters' button press but I cannot find a way to have this clear the search filter and have it reset it's filtered data.

  // This is my data source that is used in the template
  dataSource = new MatTableDataSource<MyObj>();

  // ... more code here ...

  clearFilters(){
        //clear other filters here

        //I want clear dataSource's search filter... but how?
  }

I haven't seen this posted anywhere else and doing things like dataSource.filter = "" or dataSource.filter = null then updating observers does not clear the text field or yield any results.


Solution

  • Set filter property to an empty string.

    clearFilters(){
       this.dataSource.filter = '';
    }
    


    In addition to that bind a model to the element and reset the filter input value as well.

    Template :

    <mat-form-field class="this-is-a-class" floatLabel="never">
      <mat-icon matPrefix>search</mat-icon>
      <input matInput type="text" [(ngModel)]="filter" #ctrl="ngModel" (keyup)="applySearchFilter($event.target.value)" placeholder="Search by ID or Address..." autocomplete="off"> </mat-form-field>
    

    TS :

    filter:string;
    
    clearFilters(){
       this.dataSource.filter = '';
       this.filter = '';
    }