2

I have defined a ngx-datatable in my Angular6 project as follows and I need to sort the countries in below order in the table.

Code-

<ngx-datatable [rows]="rows" [limit]="20" [rowHeight]="35" [headerHeight]="35" [footerHeight]="35" [scrollbarV]="true"
[columnMode]="'force'" class="material">
<ngx-datatable-column prop="name" name="name">
    <ng-template ngx-datatable-cell-template let-value="value">
        {{value}}
    </ng-template>
</ngx-datatable-column>
<ngx-datatable-column prop="country" name="country">
    <ng-template ngx-datatable-cell-template let-value="value">
        {{value}}
    </ng-template>
</ngx-datatable-column>

Order of the rows should be -  England > America > Russia

I can order columns Alphabetically as follows.

[sorts]="[{prop: 'country'}"

But I need to sort them as in above order. Rows are in this order. (England > America > Russia).

Please help me with the sorting or using a custom comparator in ngx-databale. Thanks

Sample code in stackblitz

11
  • What is this sorting called? There is nothing seems related to sorting here. It's not called sorting, it is how you want to display your data. You need to make custom logic or whatever for this. Commented Dec 20, 2019 at 9:47
  • @SurjeetBhadauriya Sorting columns in above order rather than in alphabetical order. If it is a column with numbers, it is easy to sort. But I need to sort it from specific values. Commented Dec 20, 2019 at 9:49
  • @SurjeetBhadauriya yes..sorting means, displaying rows in above order. Commented Dec 20, 2019 at 9:51
  • 1
    can you try creating a demo on stackblitz Commented Dec 20, 2019 at 9:52
  • 1
    first sort it with name using custom sort function same as county , instead of country , check for name, once it is sorted, then again call another sort function with country. You can generalize the sort function with an option to pass property name to the function. Commented Dec 20, 2019 at 11:32

1 Answer 1

2

You can create custom comparator function like below

  order = ['England', 'America', 'Russia'];

this.rows.sort((propA, propB) => {
       let indexA = this.order.indexOf(propA.country);
       let indexB = this.order.indexOf(propB.country);

       if (indexA > indexB) {

          return 1;
        } else if (indexA < indexB) {

          return -1;
        }

      return 0;
    });

here is the demo - https://stackblitz.com/edit/ngx-column-reordering-bl4kdh Hope this helps

Sign up to request clarification or add additional context in comments.

1 Comment

This is only work in initialize time. After each click on header the data will sort by default!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.