Angular Kendo UI offers the ability to customize the way grid columns are sorted

I'm currently working on a Kendo Grid (UI for Jquery) where I have implemented a custom sort method for a specific column based on my customers' requirements.

field: "daysLeft",
title: "Accessible",
width: 130,
sortable: {
  compare: function (a, b, descending) {
    if (a.daysLeft == 'Not started') return 1;
    if (b.daysLeft == 'Not started') return -1;
    if (a.end < b.end) return -1;
    if (a.end > b.end) return +1;
    return 0;
  }
}

I have replicated the same grid in Kendo UI for Angular, using Angular 6, and everything is working well except for the custom sort method mentioned above. All other columns are sorting correctly using the standard method.

<kendo-grid class="m-2"
[data]="view"
[pageSize]="pageSize"
[skip]="skip"
pageable="gridSettings()"
filterable="menu"
[filter]="state.filter"
height="450"
sortable="{ allowUnsort: true, mode: multiple ? 'multiple' : 'single' }"
[sort]="state.sort"
(pageChange)="pageChange($event)"
(dataStateChange)="dataStateChange($event)"
>

This is the function I am currently using for dataStateChange:

public dataStateChange(state: DataStateChangeEvent): void {
  this.state = state;
  this.view = process(this.items, this.state);
}

I am wondering if it is possible to achieve the same custom sorting functionality in Kendo UI for Angular.

Answer №1

Due to the current unavailability of a solution, I improvised a temporary fix for my specific issue. Sharing it here in case it can assist someone else.

In my grid setup, I included the following line:

(sortChange)="sortChange($event)"

Here is how my sortChange function is implemented:

public sortChange(sort: SortDescriptor[]): void {
  sort.map((item) =>
  {
    if (item.field == "daysLeft")
    {
      if(item.dir === undefined) this.view.data === this.items;
      var data = this.view.data.sort((a, b) => {
      var aend = parseInt(a.end.substr(6));
      var bend = parseInt(b.end.substr(6));
      if (a.daysLeft == 'Not started') return +1;
      if (b.daysLeft == 'Not started') return -1;
      if (aend < bend) return -1;
      if (aend > bend) return +1;
      return 0;
    });
    if(item.dir === "desc") {
      data = data.reverse();
    }
     this.view.data = data; 
  }
 });
}

The object this.view represents my GridDataResult.

Answer №2

Daedalus' assistance was invaluable to me, with just a few minor adjustments needed as follows:

public updateSort(sort: SortDescriptor[]): void {
    sort.map((item) =>
    {
        if (item.field == "daysLeft")
        {
            if (item.dir === undefined) {
                this.display.data = this.items;
            } else {
                var newData = this.display.data.sort((a, b) => {
                    var aEnd = parseInt(a.end.substr(6));
                    var bEnd = parseInt(b.end.substr(6));
                    if (a.daysLeft == 'Not started') return +1;
                    if (b.daysLeft == 'Not started') return -1;
                    if (aEnd < bEnd) return -1;
                    if (aEnd > bEnd) return +1;
                    return 0;
                 });
            if (item.dir === "desc") {
                newData = newData.reverse();
            }
            this.display.data = newData; 
            this.sort["dir"] = item.dir;
         } else {
             this.sort = sort;
             this.loadData();
         }
    });
}

Additionally, remember to include "banana in a box" for data and sort in the HTML like this: [(sort)]="sort"

Answer №3

adjust the sorting functionality by making the following changes:

    (sortChange)="sortChange($event)"

include a column that should be sorted in descending order first, rather than ascending, in the list below

      public resortColumn:any[] =['UnitPrice'];

specify the sorting change function as outlined below

        public sortChange(sort: SortDescriptor[]): void {
  if(this.resortColumn.indexOf(sort[0].field) != -1 )
  {
    if(sort[0].dir == "desc")
    {
      sort[0].dir = undefined;
    }
    else if(sort[0].dir == "asc")
    {
       sort[0].dir = "desc";
    }
    else if(sort[0].dir == undefined)
    {
        sort[0].dir = "asc";
    }
  }

    this.sort = sort;
    this.loadProducts();
}

Check out the changes in action by clicking on the following link: https://stackblitz.com/edit/angular-dsmrz2-37jaa5?file=app/app.component.ts

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a secure alternative in Typescript for handling null values, such as a "safe operator"?

I'm currently working on implementing a feature in my Angular application where I need to toggle the visibility of a div using ngIf. Below you can find the snippet of HTML code I am using: <div *ngIf="damageReportToPolice()"> </div> Her ...

Setting up Angular 2 for Highcharts: A Comprehensive Guide

Having trouble implementing a highchart component in my Angular 2 project after setting it up with the latest version. I've created a linechart component directory and tried to add the chart using the <line-chart></line-chart> tag in the H ...

Embracing the power of Typescript with Node and Express?

While trying out the TypeScript Node Starter project from Microsoft, I found myself intrigued. Is it really possible to use TypeScript instead of Node on the server? There are a number of server-side tasks where TypeScript excels: - Building a web API ser ...

Extending Error object disrupts `instanceof` validation in TypeScript

Could someone clarify why the error instanceof CustomError part of the code below returns false? class CustomError extends Error {} const error = new CustomError(); console.log(error instanceof Error); // true console.log(error instanceof CustomError); ...

When attempting to run a Typescript Playwright test in Visual Studio Code's debug mode, it inexplicably fails to execute

I am fairly new to TypeScript and Playwright, but I have experience in coding. I believe I have a good understanding of what I am trying to achieve, but I am encountering a problem that I can't seem to figure out. I'm hoping someone can help me. ...

Modify the data type of an object member based on its original type

I am seeking to convert the data type of each member in an object based on the specific member variable. Here is an example: class A { fct = (): string => 'blabla'; } class B { fct = (): number => 1; } class C { fct = (): { o ...

Tips for positioning the border properly within a scrollable table

My table has a sticky header with a fixed height, and in order to see more rows in the table, we have to scroll through them. The table design includes borders. The problem arises when there are more rows, as the border moves with the scroll. Initially, ...

updating an object using its instance in angular: step-by-step guide

Having multiple nested arrays displaying data through HTML recursion in Angular, I am faced with the task of updating specific fields. Directly editing a field is simple and involves assigning its instance to a variable. arr=[{ "name":"f ...

Transition your PHP application to Angular gradually

Our current setup consists of a Multi Page PHP Application that we are looking to migrate to Angular 4 in stages. This will allow us to gradually transition our modules over the span of a few months. While we have Node.js installed on our localhost testin ...

What is the simplest method to customize or enhance Angular 5 directives with Angular-material?

In my Angular5 application, I am utilizing the angular-material library in some areas. However, I prefer to maintain a level of agnosticism in my markup when it comes to external libraries. Despite this, I attempted the following approach: import { Direc ...

Angular version 4 JSONP request callback

Currently, I am working on the migration of an Angular 1 application to Angular 4. One particular challenge I have encountered is a jsonp call to an endpoint over which I have no control. In the Angular 1 app, the following code snippet is being used: js ...

What is the reason behind the return type of 'MyType | undefined' for Array<MyType>.find(...) method?

Currently, I am in the process of developing an Angular application using TypeScript. As part of this project, I have defined several classes along with corresponding interfaces that align perfectly with their respective properties: Map: export class Map ...

What is the best way to merge import all with different elements?

My TSLint is flagging the following issue: Multiple imports from 'moment' can be combined into one. Here is the code causing the problem: import * as moment from 'moment'; import { Moment } from 'moment'; I have attempted ...

How can we identify all the foreign_key1 ids from a MySQL join table that have a specific foreign_key2 assigned to them that is within a specified list?

I have a scenario where I have two tables, Table A and Table B, connected by a many-to-many relationship. Table A: ID --- 1 2 3 Table B: ID --- 4 5 6 7 Table AB: ID | A_ID | B_ID ---------------- 8 | 1 | 4 9 | 1 | 5 10 | 1 | 6 11 | 1 | 7 ...

Managing errors with the RxJS retry operator

I'm facing an issue with my RxJS code where I need to continuously retry a data request upon failure while also handling the error. Currently, I am using the retry operator for this purpose. However, when attempting to subscribe to the retry operator ...

Dealing with the endless looping problem in Next.js caused by useEffect

Looking to implement a preloader that spins while the content is loading and disappears once the loading is complete. However, encountering an issue where the site gets stuck on the loading page and keeps loading infinitely. I've tried multiple soluti ...

Final Page Index (Backend pagination with Ng2-Smart-Table)

Currently, I am utilizing the Ng2-Smart-Table component along with server-side pagination. Upon testing out the provided example, I delved into the requests being made and noticed that only JSON records or objects were being returned. Here is an example of ...

Enhance your Typescript code with a type guard that supports optional wrapped types

I haven't come across a question similar to this one before. My goal is to develop a type guard that can accurately determine the type of a specific variable. It's quite simple with a single type. type A = { id: number, title: string, type: stri ...

What is the alternative parameter to use instead of onChange in React Router v4?

Having an issue with the onChange Prop in TypeScript and React JS: I am encountering an error message saying "No overload matched this call." <HashRouter> <Switch> <Route path="/" ...

Tips on avoiding updates to a defined object when a new object is filtered (created from the original object)

Is there a way to filter an array of objects based on their year without altering the original object? Whenever I apply a filter, it affects both the newly created object and the original one. However, I need the original object to remain unchanged so that ...