Maitree Kuria
Maitree Kuria

Reputation: 72

How to use custom sort function on column header click, angular 6 + ngx-easy-table library

Angular version: 6
Table library: ngx-easy-table
Library reference links:
https://stackblitz.com/edit/ngx-easy-table?file=app%2Fcomponents%2Fserver-sort%2Fserver-sort.component.ts
https://github.com/ssuperczynski/ngx-easy-table/wiki

Using the above table library, I want to sort certain columns using my custom sort function on the click of that particular column header/title. There is an example of custom sort in the stackblitz link provided above which enables us to do that but by placing a separate button for each column.

Also, am using <ng-template> to render the table data as below:

<ngx-table [configuration]="configuration" [data]="upcomingBookingsList" [columns]="columns" (event)="eventEmitted($event)">
  <ng-template let-row>
    <td>
      <a class="list-id-styles" (click)="openBookingDetailsModal(row['id'])">{{row.id}}</a>
    </td>
    <td>
      {{row.webStatus}}
    </td>
    <td>
      {{row.guestDOB }}
    </td>
    <td>
      {{row.startDateNTime }}
    </td>
    <td>
      {{row.updateDate }}
    </td>
  </ng-template>
</ngx-table>

It would be great to get some help on this!

Upvotes: 1

Views: 2940

Answers (1)

ssuperczynski
ssuperczynski

Reputation: 3416

I'm the creator of this library. Solution is really simple. Please check link here where this example is described.

You need to check in the eventEmitted method which header key has been clicked. Then call your custom sort method, in this case sortByLastName

eventEmitted($event) {
  if ($event.event === 'onOrder') {
    if ($event.value.key === 'name') {
      this.sortByLastName($event.value.order === 'asc');
    }
}
private sortByLastName(asc: boolean): void {
  this.data = [...this.data.sort((a, b) => {
    const nameA = a.name.toLowerCase().split(' ')[1];
    const nameB = b.name.toLowerCase().split(' ')[1];
    if (nameA < nameB) {
      return asc ? -1 : 1;
    }
    if (nameA > nameB) {
      return asc ? 1 : -1;
    }
    return 0;
  })];
}

Upvotes: 1

Related Questions