3

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.

JamieT
  • 1,177
  • 1
  • 9
  • 19

1 Answers1

15

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 = '';
}
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • 1
    Like I said at the end of my question, this doesn't work. The text remains in the search field. – JamieT Apr 05 '19 at 18:09
  • @JamieTaylorSangerman : can you share your template and ts file – Pranav C Balan Apr 05 '19 at 18:13
  • I was not aware that (or didn't think) you could bind the value to the ngModel like that. Works like a charm. Thank you! – JamieT Apr 05 '19 at 18:28
  • Worked for me with added alterations. After I added button . Further imported the MatIconModule in my .module.ts file and added a @import url("https://fonts.googleapis.com/icon?family=Material+Icons"); in my .scss file to render a small cross icon instead of button. – vinsinraw Dec 16 '19 at 12:36