我正在为 Angular 使用 Kendo UI Grid。 Angular 版本为 5,使用 TypeScript。
主要问题是网格将日期呈现为字符串,当应用日期过滤器时,它会尝试将字符串类型与本质上不兼容的日期类型进行比较。
为了规避这个问题,我使用了moment.js 库,它可以将字符串转换为日期格式,或者将日期转换为字符串格式,以便在两者之间进行比较。
确保您在项目中正确引用了 momentjs。将此添加到您的 component.ts(在类导出之外,因为以下是纯 javascript 代码)。
class Range {
from: Date;
to: Date;
}
// Custom Filter Operator: isWithin
function isWithin(columnValue: Date, range: Range): boolean {
if (columnValue) {
return moment(columnValue).isBetween(moment(range.from), moment(range.to), 'minute', '[]');
} else {
return false;
}
}
以下是 component.ts 中的打字稿代码,它基本上将自定义过滤器添加到 Kendo Grid 的过滤器中。每当更新日期选择器中的值时都会调用 onMinDateChange 和 onMaxDateChange 函数(请参阅 component.html 的代码),并且过滤器会自动更新。
public onMinDateChange(value: Date): void {
this.filterDateRange(value, this.filterValueDateMax);
}
public onMaxDateChange(value: Date): void {
this.filterDateRange(this.filterValueDateMin, value);
}
public filterDateRange(min, max): void {
this.filter.filters = [];
if (min && max) {
this.filter.filters.push({
field: this.field,
operator: isWithin,
value: { from: min, to: max }
});
}
}
通过在component.ts中添加这一行来输入过滤器:
@Input() public filter: CompositeFilterDescriptor;
日期时间选择器(如果需要,可以只使用日期选择器)在 component.html 中定义如下:
<div class="row">
<kendo-datepicker [(value)]="filterValueDateMin" [format]="'MM/dd/yyyy HH:mm:ss'" (valueChange)="onMinDateChange($event)"> </kendo-datepicker>
<kendo-timepicker [(value)]="filterValueDateMin" (valueChange)="onMinDateChange($event)"> </kendo-timepicker>
</div>
<div class="row">
<kendo-datepicker [(value)]="filterValueDateMax" [format]="'MM/dd/yyyy HH:mm:ss'" (valueChange)="onMaxDateChange($event)"> </kendo-datepicker>
<kendo-timepicker [(value)]="filterValueDateMax" (valueChange)="onMaxDateChange($event)"> </kendo-timepicker>
</div>
最后,这就是我在主网格的 html 中使用过滤器的方式:
<ng-template kendoGridFilterMenuTemplate *ngIf="col.fieldName === 'insertFieldNameHere'"
let-filter="filter"
let-column="column"
let-filterService="filterService">
<app-date-time-range-filter [headerTitle]="col.displayName"
[filter]="filter"
[field]="column.field">
</app-date-time-range-filter>
</ng-template>
希望这会有所帮助。