HTML:
<p-dataTable
[value]="table.rows"
(onSort)="sortColumn($event)">
<p-column
*ngFor="let column of table.columns"
[field]="column.field"
[header]="column.header"
sortable="custom">
// All your columns and stuff and your data and all that </p-column>
</p-dataTable>
TS:
// Add this line at the end of your imports, before the @Component annotation:
import * as moment from 'moment';
// If that doesn't work, you may have to add this instead:
const moment = require('moment');
// Then, in your component body add this:
public dateFieldFormat:string = 'MM/DD/YYYY';
public table; //Assuming this is the data you're passing in. Some sort of JSON with an array of rows and an array of columns
isDateColumn(columnTitle: string) {
for (const row of this.table.rows) {
const value = row[columnTitle];
if (!moment(value, this.dateFieldFormat).isValid() && value !== null) {
return false;
}
}
return true;
}
sortColumn(eventPayload: any): void {
this.sort(eventPayload);
this.table.rows = [...this.table.rows];
}
sort(event: any): Array<any> {
return this.table.rows.sort((item1, item2) => {
const value1: string = item1[event.field];
const value2: string = item2[event.field];
if (value1 === null) {
return 1;
}
if (this.isDateColumn(event.field)) {
const date1 = moment(value1, this.dateFieldFormat);
const date2 = moment(value2, this.dateFieldFormat);
let result: number = -1;
if (moment(date2).isBefore(date1, 'day')) { result = 1; }
return result * event.order;
}
let result = null;
if (value1 == null && value2 != null) {
result = -1;
} else if (value1 != null && value2 == null) {
result = 1;
} else if (value1 == null && value2 == null) {
result = 0;
} else if (typeof value1 === 'string' && typeof value2 === 'string') {
result = value1.localeCompare(value2);
} else {
result = (value1 < value2) ? -1 : (value1 > value2) ? 1 : 0;
}
return (event.order * result);
});
}
primeng 4.3.0
Угловой 4.3.6
также с использованием MomentJS , который прост в использовании:)
Я создал это сам и широко его использовал.Когда вы сортируете столбец, он проверяет, есть ли в столбце, который вы пытаетесь отсортировать, ТОЛЬКО даты.И если это произойдет, он будет использовать MomentJS для проверки значений на основе хронологии.В противном случае он будет отсортирован по алфавиту.Код для сортировки по алфавиту происходит непосредственно из исходного кода primeNG, поэтому не беспокойтесь о его неправильной работе:)
Кроме того, если в столбце с датами есть нулевые значения, они всегда будут наснизу, независимо от того, как вы сортируете, вверх или вниз.
Спасибо также ребятам в этом вопросе: PrimeNG DataTable Custom Сортировка или фильтрация (Angular 2) для запуска меня.
Надеюсь, я ясно дал понять.Дайте мне знать, как я могу улучшить свой ответ, если он неясен или не работает для вас.