首页 > 解决方案 > 我如何为日期编写自定义过滤函数

问题描述

我有一个带有时间戳列的 DataTable:

<p-dataTable sortMode="multiple" scrollable="scrollable" scrollHeight="150" [value]="currentChartData" #dt>
        <p-column field="timestamp" header="Timestamp" [sortable]="true" [filter]="true">
            <ng-template pTemplate="filter" let-col>
                <div class="d-flex flex-row flex-wrap justify-content-center align-content-center">
                    <div style="padding-right: 29px">
                        <p-calendar [(ngModel)]="from" [showTime]="true"
                                    (onSelect)="filter(dt, 'from')"
                                    (onClearClick)="filter(dt, 'from')"
                                    showButtonBar="true" readonlyInput="true"
                                    [inputStyle]="{'width': '8em'}" styleClass="ui-column-filter" appendTo="body"
                                    dateFormat="dd.mm.yy">
                        </p-calendar>
                    </div>
                    <div style="padding-right: 29px">
                        <p-calendar [(ngModel)]="to" [showTime]="true"
                                    (onSelect)="filter(dt, 'to')"
                                    (onClearClick)="filter(dt, 'to')"
                                    showButtonBar="true" readonlyInput="true"
                                    [inputStyle]="{'width': '8em'}" styleClass="ui-column-filter" appendTo="body"
                                    dateFormat="dd.mm.yy">
                        </p-calendar>
                    </div>
                </div>
            </ng-template>
            <ng-template let-row="rowData" pTemplate="body">
                {{row.timestamp.toLocaleString()}}
            </ng-template>
        </p-column></p-dataTable>

我想为过滤字段“from”和“to”使用两个日历,以便过滤两个日期之间的行。

我的过滤器功能如下所示:

between(value: any, from: any, to: any): boolean {
    if (from === undefined || from === null) {
        return true;
    }
    if (to === undefined || to === null) {
        return false;
    }
    if ((from === undefined || from === null ||
         (typeof from === 'string' && from.trim() === '') || from <= value) &&
        (to === undefined || to === null ||
         (typeof to === 'string' && to.trim() === '') || to >= value)) {
        return true;
    }
    return false;
};

通常,您使用 对数据表执行过滤器dt.filter()。我如何能够覆盖它以使用我的 between 函数进行过滤。的返回值是dt.filter()多少?

标签: angulartypescriptprimengprimeng-datatable

解决方案


I injected the new filterConstraint into the Datatable with

@ViewChild('dt') dataTable: DataTable;

ngAfterViewChecked() {
    if (this.dataTable !== undefined) {
        const customFilterConstraints = this.dataTable.filterConstraints;
        customFilterConstraints[ 'between' ] = this.between; 
        this.dataTable.filterConstraints = customFilterConstraints;
    }
}

推荐阅读