我目前正在尝试在我的应用程序中实现排序功能。无论出于何种原因,我被要求在不使用Pipes的情况下实施。我已经使用Stack
中不同答案的javascript排序答案之一编写了导出类和排序功能问题: - 我需要在表格中对列中的特定列进行排序,并且我相信我在点击时对排序的实现是错误的。
表分拣service.ts
import { Injectable } from '@angular/core';
@Injectable()
export class TableSortingService {
tableSort(sortField, sortDirection, sortEntityType) {
let key = sortEntityType ?
function(field) { return sortEntityType(field[sortField]); } :
function(field) { return field[sortField]; };
sortDirection = !sortDirection ? 1 : -1;
return function(fieldToSort, directionToSort) {
return fieldToSort = key(fieldToSort), directionToSort
= key(directionToSort), sortDirection * (<any>(fieldToSort > directionToSort) - (<any>(directionToSort > fieldToSort)));
};
}
}
在我的component.ts
中 sortDate(invoices) {
this.invoices.sort(this.tableSortService.tableSort('dateOfService', true, function (invoiceSummary) {
return new Date(invoiceSummary.dateOfService) ;
}));
// console.log(this.sortDate);
};
ngOnInit() {
this.invoics = xyz data retreived from the service;
}
HTML: -
<table class="table table-invoices hover">
<thead>
<tr>
<th></th>
<th>Invoice</th>
<th (click)="sortDate()">Date</th>
<th class="text-right full-width">Amount</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let invoice of invoices">
<td>{{ invoice.invoiceNumber }}</td>
<td>{{ invoice.dateOfService | date:'shortDate' }}</td>
<td class="amount text-right">
{{ invoice.balanceDue | currency:'USD':true }}</td>
</tr>
</tbody>
</table>
P.S: - 上面的类是在以下堆栈溢出问题的帮助下实现的 https://stackoverflow.com/a/979325/5290012