Search code examples
angular-materialangular-material-tableangular15

Is there a way to search date for the angular material table


<mat-form-field class="searchbar" appearance="outline"> <input matInput (keyup)="applyFilter($event)" placeholder="Search ..." #input /> this is my search bar using matInput.

applyFilter(event: Event) { const filterValue = (event.target as HTMLInputElement).value; this.dataSource.filter = filterValue.trim().toLowerCase(); } this is my search filter function.

Isit able to search date format like 20/02/2024 and the table will show based on the date input without using datepicker.

Example of searching date format


Solution

  • We can just add the filterPredicate with the condition to check the formatted date.

    this.dataSource.filterPredicate = (data: any, filter: string) => {
      console.log(data, filter, format(data.bookingDate, 'dd/mm/yyyy'));
      return (
        data.name.indexOf(filter) != -1 ||
        format(new Date(data.bookingDate), 'dd/mm/yyyy').indexOf(filter) != -1
      );
    };
    

    I am using an external package date-fns to format the date before doing the comparison!

    full code

    import { Component } from '@angular/core';
    import { MatRippleModule } from '@angular/material/core';
    import { MatFormFieldModule } from '@angular/material/form-field';
    import { MatTableDataSource, MatTableModule } from '@angular/material/table';
    import { MatInputModule } from '@angular/material/input';
    import { CommonModule } from '@angular/common';
    import { format } from 'date-fns';
    function randomDate(start: any = new Date(2012, 0, 1), end: any = new Date()) {
      return new Date(
        start.getTime() + Math.random() * (end.getTime() - start.getTime())
      );
    }
    
    const ELEMENT_DATA = [
      { name: 'Hydrogen', bookingDate: randomDate() },
      { name: 'Helium', bookingDate: randomDate() },
      { name: 'Lithium', bookingDate: randomDate() },
      { name: 'Beryllium', bookingDate: randomDate() },
      { name: 'Boron', bookingDate: randomDate() },
      { name: 'Carbon', bookingDate: randomDate() },
      { name: 'Nitrogen', bookingDate: randomDate() },
      { name: 'Oxygen', bookingDate: randomDate() },
      { name: 'Fluorine', bookingDate: randomDate() },
      { name: 'Neon', bookingDate: randomDate() },
    ];
    
    /**
     * @title Tables with Material Design ripples.
     */
    @Component({
      selector: 'table-with-ripples-example',
      templateUrl: 'table-with-ripples-example.html',
      standalone: true,
      imports: [
        MatTableModule,
        MatRippleModule,
        MatFormFieldModule,
        MatInputModule,
        CommonModule,
      ],
    })
    export class TableWithRipplesExample {
      displayedColumns: string[] = ['name', 'bookingDate'];
      dataSource = new MatTableDataSource(ELEMENT_DATA);
    
      ngOnInit() {
        this.dataSource.filterPredicate = (data: any, filter: string) => {
          console.log(data, filter, format(data.bookingDate, 'dd/mm/yyyy'));
          return (
            data.name.indexOf(filter) != -1 ||
            format(new Date(data.bookingDate), 'dd/mm/yyyy').indexOf(filter) != -1
          );
        };
      }
    
      applyFilter(event: Event) {
        const filterValue = (event.target as HTMLInputElement).value;
        this.dataSource.filter = filterValue.trim().toLowerCase();
      }
    }
    

    html

    <mat-form-field class="searchbar" appearance="outline">
      <input
        matInput
        (keyup)="applyFilter($event)"
        placeholder="Search ..."
        #input
      />
    </mat-form-field>
    <mat-table [dataSource]="dataSource" class="mat-elevation-z8">
      <ng-container matColumnDef="name">
        <mat-header-cell mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
        <mat-cell mat-cell *matCellDef="let element"> {{element.name}} </mat-cell>
      </ng-container>
      <ng-container matColumnDef="bookingDate">
        <mat-header-cell mat-header-cell *matHeaderCellDef>
          Booking Date
        </mat-header-cell>
        <mat-cell mat-cell *matCellDef="let element">
          {{element.bookingDate | date : 'dd/mm/yyyy'}}
        </mat-cell>
      </ng-container>
    
      <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
      <mat-row matRipple *matRowDef="let row; columns: displayedColumns;"></mat-row>
    </mat-table>
    

    Stackblitz Demo