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.
"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.