Parinda Rajapaksha
Parinda Rajapaksha

Reputation: 3117

How to write a custom sorting method for ngx-datatable column in Angular6?

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

Upvotes: 2

Views: 5726

Answers (1)

Allabakash
Allabakash

Reputation: 2027

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

Upvotes: 2

Related Questions