mariuszfoltak / angular2-datatable

DataTable - Simple table component with sorting and pagination for Angular2
202 stars 182 forks source link

Custom functions in sortBy? #47

Closed amellnik closed 8 years ago

amellnik commented 8 years ago

Should I be able to do something like

<th><mfDefaultSorter by="[function(o) { return o.user; }]">User</mfDefaultSorter></th>

or are only column names supported? (This is a trivial example -- I need to modify the sorting function to display nulls last for both ascending and descending sorts).

mariuszfoltak commented 8 years ago

Yes, you can pass function to sorter. You can check examples/systemjs/app/app.component.ts (look at sortByWordLength function) for example.

mariuszfoltak commented 8 years ago

Example, I was wrote about, not working (function sortByWordLength is never used), but you can check it in this plunker. Function sortByWordLength is used for city sorter

amellnik commented 8 years ago

Thanks @mariuszfoltak!

In case anyone else looks at this issue later -- if you have dynamic columns it's also possible to dynamically define the sort functions. For example:

In component-name.component.ts:

  private sortFnClosure(colName:string) {
    return new Function('a', `return a['${colName}'].length;`);
  }

In component-name.component.html

<thead><tr>
  ...
  <th *ngFor="let col of cols">
    <mfDefaultSorter [by]="sortFnClosure(col)">
      col
    </mfDefaultSorter>
  </th>
</tr></thead>
priyankakolee commented 7 years ago

@mariuszfoltak Here we can edit the sortBy, any way to edit the sortOrder? I wish to make column sorting to be descending by default, on first click column should be sorted descending instead of ascending(which is default).