angularprimengprimeng-turbotable

Filtering TurboTable by dates


I have simple TurboTable where I show some data, including dates.

<p-table [value]="boxes" #dt>
    <ng-template pTemplate="header" let-columns>
        <tr>
            <th pSortableColumn="Number">
                Number
                <p-sortIcon field="Number"></p-sortIcon>
            </th>
            <th pSortableColumn="DateInserted">
                Interted at
                <p-sortIcon field="DateInserted"></p-sortIcon>
            </th>
        </tr>
        <tr>
            <th>
            <!-- Here is input to filter number -->
            </th>
            <th>
            <!-- Here I want to use Calendar component to select date range -->
            <p-calendar 
                [(ngModel)]="date"
                selectionMode="range"
                [readonlyInput]="true"
                dateFormat="dd.mm.yy"
                (onSelect)="onDateSelect($event)">
            </th>
        </tr>
    </ng-template>
    <ng-template pTemplate="body" let-box>
        <tr [pSelectableRow]="box">
            <td>{{box.Number}}</td>
            <td>{{box.DateInserted | date}}</td>
        </tr>
    </ng-template>
</p-table>

Currently Turbo Table offers only a few match modes to use in filters ( "startsWith", "contains", "endsWith", "equals" and "in"). Is there any option to filter by date or date ranges?

I want to use the Calendar component to select a date range and then filter data by these dates. I am using Date objects (which I present in Table with DatePipe). Now none of these match modes offers option to compare Date objects correctly.

The workaround is to store dates as strings, and then filtering is working. But is is not perfect solution, because it generates problems with converting dates to strings, also date format must be this same everywhere. So maybe there is better option to achieve filtering by date ranges in TurboTable?


Solution

  • As a workaround, you can add a custom behavior quite simple for the moment.

    <p-calendar 
        [(ngModel)]="date"
        selectionMode="range"
        [readonlyInput]="true"
        dateFormat="dd.mm.yy"
        (onSelect)="dt.filter($event, 'DateInserted', 'my')">
    

    Then, in your component you can do this:

    import Table from 'primeng/table';
    ...
    @Component({...})
    export MyComponent implements OnInit {
        @ViewChild('dt') private _table: Table;
        ngOnInit(){
            this._table.filterConstraints['my'] = (value, filter): boolean => {
                // Make sure the value and the filter are Dates
                return value.getTime() == filter.getTime();
            }
        }
    }