1

I am currently trying to implement a sorting functionality in my application. I was asked to implement without using Pipes for whatever reason. I have written the export class and sort functionality using one of the answers for javascript sorting from a different answer here in Stack

Question:-- I need the particular column in the table to sort when I click and I believe my implementation of sorting on click is wrong.

table-sorting-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)));
      };
  }
}

in my 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:-- the above class was implemented with the help of the following stack overflow question https://stackoverflow.com/a/979325/5290012

Community
  • 1
  • 1
Vijay
  • 600
  • 6
  • 16

0 Answers0