Is there a way to filter material table based on date

Viewed 7862

I'm trying to filter table based on starttime and endtime using mat datepicker. but its not working. This is my html code-

    <mat-form-field><input matInput [matDatepicker]="dp1" (keyup)="dateFilter($event.target.value,'start')" (dateInput)="addEvent($event.target.value, $event)" placeholder="Choose a date"><mat-datepicker-toggle matSuffix [for]="dp1" ></mat-datepicker-toggle<mat-datepicker #dp1 ></mat-datepicker>

this is my ts file code for manually typing date which is working-

dateFilter(filterValue : String,input)  {
debugger;
 this.dataSource.filter = filterValue.trim().toLowerCase();
 if(input=='start'){
  this.dataSource.filterPredicate = function(data, filter: string): boolean {
    return data.startTime.toLowerCase().includes(filter); };} else{ this.dataSource.filterPredicate = function(data, filter: string): boolean {
    return data.endTime.toLowerCase().includes(filter);
};
}  }

this function to choose the date from datepicker which is not working -

addEvent(filterValue: string, event: MatDatepickerInputEvent<Date>) {
  debugger;
  console.log(event.value);
  if(event.value!=undefined){
    filterValue =this.datepipe.transform(filterValue, 'MM/dd/yyyy');
  } 
  this.dataSource.filter = filterValue.trim();
  this.dataSource.filterPredicate = function(data, filter: string): boolean {
  return data.startTime.includes(filter);
};
1 Answers

Use M/d/yyyy format to parse the date from DatePicker like:

this.datepipe.transform(filterValue, 'M/d/yyyy');

as per your JSON data, it actually does not contains leading zero's.

Working_Demo

I selected 1st May 2019 from the date picker and got the first record in the result.

EDIT:

You need to register a filterPredicate once and then you can set filter property of DataSource

So just register it in constructor or ngOnInit() method like:

constructor(public datepipe: DatePipe) {
    this.dataSource.filterPredicate = (data, filter: string) => 
        !filter || data.startTime.includes(filter);
}

and on click event just:

this.dataSource.filter = filterValue.trim();
Related