PrimeNG datatable date range filter
Asked Answered
A

3

11

Filter date range || Datatable

I need some help on how to filter date range..dateCreated

I want to search date created in search input, but it seems, it's not working. No records found. I was searching about custom filter, and I'm having a hard time how to do it.

I'm using momentjs.

Abdication answered 30/4, 2018 at 10:24 Comment(0)
W
21

"p-dataTable" is deprecated and therefore my solution uses the newer "p-table".

Too accomplish this you need to add your own constraint for the range filter:

First you need to add a reference to your table in your component:

@ViewChild('myTable') private _table: Table;

Use it to add a new entry to the tables filterConstraints array:

ngOnInit() {
  var _self = this;
  // this will be called from your templates onSelect event
  this._table.filterConstraints['dateRangeFilter'] = (value, filter): boolean => {
    // get the from/start value
    var s = _self.dateFilters[0].getTime();
    var e;
    // the to/end value might not be set
    // use the from/start date and add 1 day
    // or the to/end date and add 1 day
    if ( _self.dateFilters[1]) {
      e =  _self.dateFilters[1].getTime() + 86400000;
    } else {
      e = s + 86400000;
    }
    // compare it to the actual values
    return value.getTime() >= s && value.getTime() <= e;
  }
}

Add a variable to hold the start and end date values and make sure you have the FormsModule added to your module:

dateFilters: any;

In your template you need to add this variable as the model for a p-calendar. Also the onSelect event of the p-calendar needs to be set. Your template should look like the following:

<p-table #myTable [columns]="cols" [value]="data" [rows]="10">
  <ng-template pTemplate="header" let-columns>
    <tr>
      <th *ngFor="let col of columns">{{col.header}}</th>
    </tr>
    <tr>
      <th *ngFor="let col of columns" [ngSwitch]="col.field">
        <p-calendar
          [(ngModel)]="dateFilters"
          appendTo="body"
          *ngSwitchCase="'date'"
          selectionMode="range"
          [readonlyInput]="false"
          dateFormat="dd.mm.yy"
          (onSelect)="myTable.filter($event, col.field, 'dateRangeFilter')">
        </p-calendar>
      </th>
    </tr>
  </ng-template>
  <ng-template pTemplate="body" let-rowData let-columns="columns">
    <tr>
      <td *ngFor="let col of columns" [ngSwitch]="true">
        <span *ngSwitchCase="col.field === 'date'">{{rowData[col.field] | date}}</span>
        <span *ngSwitchDefault>{{rowData[col.field]}}</span>
      </td>
    </tr>
  </ng-template>
</p-table>

The data and the column definition for this example table looks like the following:

this.data = [
  { date: new Date("2018-07-12"), title: "Test1", type: "123", comment: ""},
  { date: new Date("2018-07-13"), title: "Test2", type: "123", comment: ""}
];

this.cols = [
  { field: 'date', header: 'Date'},
  { field: 'title', header: 'Title'},
  { field: 'type', header: 'Type'},
  { field: 'comment', header: 'Comment'}
];

I setup a basic example here (tested with primeNg v 6.0.1):

https://stackblitz.com/edit/angular-d252dr

Hope that gets you startet.

Ward answered 25/7, 2018 at 12:3 Comment(9)
Awsome explanation, that diserve a green tick [accepted answer]Callus
This saves my dayDictionary
If you get an error about your ViewChild variable being undefined, move the filterConstraint code to ngAfterViewInitBehr
this worked well but when I edited data on the table and rebound the data, this._table is null. Any ideas why?Brancusi
Without a minimal setup I don't think I can help you much. I setup a stackblitz which is still working. So maybe try to compare it to your setup.Ward
Definitely works! Only issue that I find is that after selecting the date range (loads correctly) and then deleting the selected date range input, the table data does not load again. It is empty. I've tried it with your stackblitz setup and I find the same issue.Grous
What is the filed "filterConstraint"? When I try to access it, I get Property 'filterConstraints' does not exist on type 'Table'.Anastasius
Yet another questions: how does Angular know what value should go here: var s = _self.dateFilters[0].getTime()? If dateFilters isdefined as any, how can one call the method getTime() on its elements?Anastasius
This line was what I wanted (onSelect)="myTable.filter($event, col.field, 'dateRangeFilter')"> much appreciatedOverdraft
V
1

If anyone is having problems with using filterConstraints and getting this error:

Property 'filterConstraints' does not exist on type 'Table'

Should switch to using the new FilterUtils.

For example:

this._table.filterConstraints['dateRangeFilter']

Becomes:

FilterUtils['dateRangeFilter']

The filter will then be available automatically for your table

Vagus answered 4/3, 2021 at 13:41 Comment(0)
E
1

FilterConstraints is no longer used, check PrimeNG documentation

https://primefaces.org/primeng/filterservice

import {FilterService} from 'primeng/api';
....
constructor(private filterService: FilterService) {}
....
this.filterService.register('dateRangeFilter', (value, filter): boolean => {
  //your code
}
Explicable answered 7/7, 2021 at 22:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.