Sorting in Angular TreeGrid component

27 Mar 202424 minutes to read

The TreeGrid component provides built-in support for sorting data-bound columns in ascending or descending order. To enable sorting in the tree grid, set the allowSorting property to true.

In the TreeGrid component, sorting follows a specific order to maintain the hierarchical structure of the data. When sorting is performed, the parent records from all rows are sorted initially. Following this, the child records within each parent are sorted internally based on the specified sorting order. This sorting process occurs within the hierarchy order once the parent records are sorted.

This behavior ensures that the hierarchical relationship between parent and child records is preserved, and child records are sorted relative to their respective parent records.

To sort a particular column in the tree grid, click on its column header. Each time you click the header, the order of the column will switch between Ascending and Descending.

To use the sorting feature, you need to inject the SortService in the provider section of AppModule.

The following demo illustrates how to enable sorting in the tree grid.

import { Component, OnInit } from '@angular/core';
import { sortData } from './datasource';

@Component({
    selector: 'app-container',
    template: `<ejs-treegrid [dataSource]='data' height='315' [treeColumnIndex]='1'  [allowSorting]='true' childMapping='subtasks' >
                    <e-columns>
                        <e-column field='Category' headerText='Category' textAlign='Right' width=140></e-column>
                        <e-column field='orderName' headerText='Order Name' textAlign='Left' width=200></e-column>
                        <e-column field='orderDate' headerText='Order Date' textAlign='Right' format='yMd' width=150></e-column>
                        <e-column field='units' headerText='Units' textAlign='Right' width=80></e-column>
                    </e-columns>
                </ejs-treegrid>`
})
export class AppComponent implements OnInit {

    public data?: Object[];

    ngOnInit(): void {
        this.data = sortData;
    }
}
import { NgModule,ViewChild } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { PageService, SortService, FilterService,ToolbarService,TreeGridModule } from '@syncfusion/ej2-angular-treegrid';
import { AppComponent } from './app.component';
import {ButtonModule} from '@syncfusion/ej2-angular-buttons';
import { DropDownListAllModule } from '@syncfusion/ej2-angular-dropdowns';

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        TreeGridModule,
        ButtonModule,
        DropDownListAllModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [PageService,
                SortService,
                FilterService,
                ToolbarService]
})
export class AppModule { }
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app.module';

import 'zone.js';
enableProdMode();
platformBrowserDynamic().bootstrapModule(AppModule);

Initial sorting

By default, the TreeGrid component does not apply any sorting to its records at initial rendering. However, you can apply initial sorting by setting the sortSettings.columns property to the desired field and sort direction. This feature is helpful when you want to display your data in a specific order when the tree grid is first loaded.

The following example demonstrates how to set sortSettings.columns for Category and orderName columns with a specified direction.

import { Component, OnInit } from '@angular/core';
import { sortData } from './datasource';

@Component({
    selector: 'app-container',
    template: `<ejs-treegrid [dataSource]='data' [treeColumnIndex]='1' height='315'  [allowSorting]='true' childMapping='subtasks' [sortSettings]='initialSort'>
                    <e-columns>
                        <e-column field='Category' headerText='Category' textAlign='Right' width=140></e-column>
                        <e-column field='orderName' headerText='Order Name' textAlign='Left' width=200></e-column>
                        <e-column field='orderDate' headerText='Order Date' textAlign='Right' format='yMd' width=150></e-column>
                        <e-column field='units' headerText='Units' textAlign='Right' width=80></e-column>
                    </e-columns>
                </ejs-treegrid>`
})
export class AppComponent implements OnInit {

    public data?: Object[];
    public initialSort?: Object;
    ngOnInit(): void {
        this.data = sortData;
        this.initialSort = { columns: [{ field: 'Category', direction: 'Ascending' }, 
                                       { field: 'orderName', direction: 'Ascending' }] };
    }
}
import { NgModule,ViewChild } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { PageService, SortService, FilterService,ToolbarService,TreeGridModule } from '@syncfusion/ej2-angular-treegrid';
import { AppComponent } from './app.component';
import {ButtonModule} from '@syncfusion/ej2-angular-buttons';
import { DropDownListAllModule } from '@syncfusion/ej2-angular-dropdowns';

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        TreeGridModule,
        ButtonModule,
        DropDownListAllModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [PageService,
                SortService,
                FilterService,
                ToolbarService]
})
export class AppModule { }
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app.module';

import 'zone.js';
enableProdMode();
platformBrowserDynamic().bootstrapModule(AppModule);

The initial sorting defined in sortSettings.columns will override any sorting applied through interaction.

Multi-column sorting

The TreeGrid component allows to sort more than one column at a time using multi-column sorting. To enable multi-column sorting in the tree grid, set the allowSorting property to true, and set the allowMultiSorting property to true which enable to sort multiple columns by hold the CTRL key and click on the column headers. This feature is useful when you want to sort your data based on multiple criteria to analyze it in various ways.

To clear multi-column sorting for a particular column, press the “Shift + mouse left click”.

  • The allowSorting must be true while enabling multi-column sort.
  • Set allowMultiSorting property as false to disable multi-column sorting.

The following demo illustrates how to enable multi-column sorting in the tree grid.

import { Component, OnInit } from '@angular/core';
import { sortData } from './datasource';

@Component({
    selector: 'app-container',
    template: `<ejs-treegrid [dataSource]='data' height='315' [treeColumnIndex]='1' [allowMultiSorting]='true' [allowSorting]='true' childMapping='subtasks' >
                    <e-columns>
                        <e-column field='Category' headerText='Category' textAlign='Right' width=140></e-column>
                        <e-column field='orderName' headerText='Order Name' textAlign='Left' width=200></e-column>
                        <e-column field='orderDate' headerText='Order Date' textAlign='Right' format='yMd' width=150></e-column>
                        <e-column field='units' headerText='Units' textAlign='Right' width=80></e-column>
                    </e-columns>
                </ejs-treegrid>`
})
export class AppComponent implements OnInit {

    public data?: Object[];

    ngOnInit(): void {
        this.data = sortData;
    }
}
import { NgModule,ViewChild } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { PageService, SortService, FilterService,ToolbarService,TreeGridModule } from '@syncfusion/ej2-angular-treegrid';
import { AppComponent } from './app.component';
import {ButtonModule} from '@syncfusion/ej2-angular-buttons';
import { DropDownListAllModule } from '@syncfusion/ej2-angular-dropdowns';

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        TreeGridModule,
        ButtonModule,
        DropDownListAllModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [PageService,
                SortService,
                FilterService,
                ToolbarService]
})
export class AppModule { }
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app.module';

import 'zone.js';
enableProdMode();
platformBrowserDynamic().bootstrapModule(AppModule);

Sort multiple columns without holding the CTRL key

You can perform multiple columns sorting without holding the CTRL key in the tree grid. This action can be achieved by enabling the enableSortMultiTouch property of the Sort module of the grid object, which can be accessed using the tree grid instance. This enableSortMultiTouch property can be enabled within the created event of the tree grid.

The following example demonstrates how to enable the enableSortMultiTouch property inside the tree grid’s created event:

import { Component, OnInit, ViewChild } from '@angular/core';
import { TreeGridComponent } from '@syncfusion/ej2-angular-treegrid';
import { sortData } from './datasource';

@Component({
  selector: 'app-container',
  template: `<ejs-treegrid #treegrid [dataSource]='data' height='315' [treeColumnIndex]='1'  [allowSorting]='true' childMapping='subtasks' (created)="created($event)" >
                    <e-columns>
                        <e-column field='Category' headerText='Category' textAlign='Right' width=140></e-column>
                        <e-column field='orderName' headerText='Order Name' textAlign='Left' width=200></e-column>
                        <e-column field='orderDate' headerText='Order Date' textAlign='Right' format='yMd' width=150></e-column>
                        <e-column field='units' headerText='Units' textAlign='Right' width=80></e-column>
                    </e-columns>
                </ejs-treegrid>`,
})
export class AppComponent implements OnInit {
  public data?: Object[];
  @ViewChild('treegrid')
  public treegrid: TreeGridComponent | undefined;

  ngOnInit(): void {
    this.data = sortData;
  }
  created(args: any) {
    (
      (this.treegrid as TreeGridComponent).grid.sortModule as any
    ).enableSortMultiTouch = true;
  }
}
import { NgModule,ViewChild } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { PageService, SortService, FilterService,ToolbarService,TreeGridModule } from '@syncfusion/ej2-angular-treegrid';
import { AppComponent } from './app.component';
import {ButtonModule} from '@syncfusion/ej2-angular-buttons';
import { DropDownListAllModule } from '@syncfusion/ej2-angular-dropdowns';

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        TreeGridModule,
        ButtonModule,
        DropDownListAllModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [PageService,
                SortService,
                FilterService,
                ToolbarService]
})
export class AppModule { }
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app.module';

import 'zone.js';
enableProdMode();
platformBrowserDynamic().bootstrapModule(AppModule);

Prevent sorting for particular column

The TreeGrid component provides the ability to prevent sorting for a particular column. This can be useful when you have certain columns that you do not want to be included in the sorting process.

It can be achieved by setting the allowSorting property of the particular column to false.

The following example demonstrates, how to disable sorting for orderName column.

import { Component, OnInit } from '@angular/core';
import { sortData } from './datasource';

@Component({
    selector: 'app-container',
    template: `<ejs-treegrid [dataSource]='data' [treeColumnIndex]='1' height='315' [allowSorting]='true' childMapping='subtasks' >
                    <e-columns>
                        <e-column field='Category' headerText='Category' textAlign='Right' width=140></e-column>
                        <e-column field='orderName' headerText='Order Name' [allowSorting]=false textAlign='Left' width=200></e-column>
                        <e-column field='orderDate' headerText='Order Date' textAlign='Right' format='yMd' width=150></e-column>
                        <e-column field='units' headerText='Units' textAlign='Right' width=80></e-column>
                    </e-columns>
                </ejs-treegrid>`
})
export class AppComponent implements OnInit {

    public data?: object[];

    ngOnInit(): void {
        this.data = sortData;
    }
}
import { NgModule,ViewChild } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { PageService, SortService, FilterService,ToolbarService,TreeGridModule } from '@syncfusion/ej2-angular-treegrid';
import { AppComponent } from './app.component';
import {ButtonModule} from '@syncfusion/ej2-angular-buttons';
import { DropDownListAllModule } from '@syncfusion/ej2-angular-dropdowns';

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        TreeGridModule,
        ButtonModule,
        DropDownListAllModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [PageService,
                SortService,
                FilterService,
                ToolbarService]
})
export class AppModule { }
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app.module';

import 'zone.js';
enableProdMode();
platformBrowserDynamic().bootstrapModule(AppModule);

Sort order

By default, the sorting order will be as ascending -> descending -> none.

When you click on a column header for the first time, it sorts the column in ascending order. Clicking the same column header again will sort the column in descending order. A repetitive third click on the same column header will clear the sorting.

Custom sorting

The TreeGrid component provides a way to customize the default sort action for a column by defining the column.sortComparer property. The sort comparer function works similar to the Array.sort comparer function, and allows to define custom sorting logic for a specific column.

In the following example, the custom sort comparer function was defined in the orderName column.

import { Component, OnInit } from '@angular/core';
import { sortData } from './datasource';

@Component({
    selector: 'app-container',
    template: `<ejs-treegrid [dataSource]='data' [treeColumnIndex]='1' height='315' [allowSorting]='true' childMapping='subtasks' >
                    <e-columns>
                        <e-column field='Category' headerText='Category' textAlign='Right' width=140></e-column>
                        <e-column field='orderName' [sortComparer]='sortComparer' headerText='Order Name' textAlign='Left' width=200></e-column>
                        <e-column field='orderDate' headerText='Order Date' textAlign='Right' format='yMd' width=150></e-column>
                        <e-column field='units' headerText='Units' textAlign='Right' width=80></e-column>
                    </e-columns>
                </ejs-treegrid>`
})
export class AppComponent implements OnInit {

    public data: Object[] = [];

    public sortComparer = (reference: string, comparer: string) => {
        if (reference < comparer) {
        return -1;
        }
        if (reference > comparer) {
        return 1;
        }
        return 0;
    };

    ngOnInit(): void {
        this.data = sortData;
    }
}
import { NgModule,ViewChild } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { PageService, SortService, FilterService,ToolbarService,TreeGridModule } from '@syncfusion/ej2-angular-treegrid';
import { AppComponent } from './app.component';
import {ButtonModule} from '@syncfusion/ej2-angular-buttons';
import { DropDownListAllModule } from '@syncfusion/ej2-angular-dropdowns';

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        TreeGridModule,
        ButtonModule,
        DropDownListAllModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [PageService,
                SortService,
                FilterService,
                ToolbarService]
})
export class AppModule { }
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app.module';

import 'zone.js';
enableProdMode();
platformBrowserDynamic().bootstrapModule(AppModule);

The customSortComparer function takes two parameters: a and b. The a and b parameters are the values to be compared. The function returns -1, 0, or 1, depending on the comparison result.

Touch interaction

When you tap tree grid header on touch screen devices, then the selected column header is sorted and display a popup Sorting for multi-column sorting, tap on the popup to sort multiple columns Multi Sorting and then tap the desired tree grid headers.

The allowMultiSorting and allowSorting should be true then only the popup will be shown.

The following screenshot represents a tree grid touch sorting in the device.

Touch interaction image

Perform sorting based on its culture

Sorting based on culture in the tree grid can be achieved by utilizing the locale property. By setting the locale property to the desired culture code, you enable sorting based on that specific culture. This allows you to apply locale-specific sorting rules and ensure accurate ordering for different languages and regions.

In the following example, sorting is performed based on the “ar” locale using the column.sortComparer property.

import { Component, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { DropDownListComponent } from '@syncfusion/ej2-angular-dropdowns';
import { TreeGridComponent } from '@syncfusion/ej2-angular-treegrid';
import { SortDirection, SortEventArgs } from '@syncfusion/ej2-grids';
import {
  L10n,
  loadCldr,
  setCulture,
  setCurrencyCode,
} from '@syncfusion/ej2-base';
import { sortData } from './datasource';
import * as cagregorian from './ca-gregorian.json';
import * as currencies from './currencies.json';
import * as numbers from './numbers.json';
import * as timeZoneNames from './timeZoneNames.json';
import * as numberingSystems from './numberingSystems.json';

@Component({
  selector: 'app-container',
  template: ` <ejs-treegrid #treegrid [dataSource]='data' height='315' [treeColumnIndex]='1'  [allowSorting]='true' locale='ar' childMapping='subtasks' >
                <e-columns>
                    <e-column field='Category' headerText='Category' textAlign='Right' width=140></e-column>
                    <e-column field='orderName' headerText='Order Name' textAlign='Left' width=200></e-column>
                    <e-column field='orderDate' headerText='Order Date' [sortComparer]="sortComparer" textAlign='Right' format='yMd' width=150></e-column>
                    <e-column field='price' headerText='Price' format='C2' type="number" [sortComparer]="sortComparer" textAlign='Right' width=80></e-column>
                </e-columns>
            </ejs-treegrid>`,
})
export class AppComponent implements OnInit {
  public data?: Object[];
  public initialSort?: Object;
  public message?: string;

  @ViewChild('treegrid')
  public treegrid?: TreeGridComponent;
  public formatOptions?: object;

  ngOnInit(): void {
    this.data = sortData;
    setCulture('ar');
    setCurrencyCode('QAR');
    loadCldr(cagregorian, currencies, numbers, timeZoneNames, numberingSystems);
    this.formatOptions = { type: 'date', format: 'yyyy/MMM/dd' };
  }
  public sortComparer = (
    reference: number | Date | string,
    comparer: number | Date | string,
    sortOrder: 'Ascending' | 'Descending'
  ) => {
    const referenceDate = new Date(reference);
    const comparerDate = new Date(comparer);
    if (typeof reference === 'number' && typeof comparer === 'number') {
      // Numeric column sorting
      return sortOrder === 'Ascending'
        ? comparer - reference
        : reference - comparer;
    } else if (
      !isNaN(referenceDate.getTime()) &&
      !isNaN(comparerDate.getTime())
    ) {
      // Date column sorting
      return sortOrder === 'Ascending'
        ? comparerDate.getTime() - referenceDate.getTime()
        : referenceDate.getTime() - comparerDate.getTime();
    } else {
      // Default sorting for other types
      const intlCollator = new Intl.Collator(undefined, {
        sensitivity: 'variant',
        usage: 'sort',
      });
      const comparisonResult = intlCollator.compare(
        String(reference),
        String(comparer)
      );
      return sortOrder === 'Ascending' ? -comparisonResult : comparisonResult;
    }
  };
}
import { NgModule,ViewChild } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { PageService, SortService, FilterService,ToolbarService,TreeGridModule } from '@syncfusion/ej2-angular-treegrid';
import { AppComponent } from './app.component';
import {ButtonModule} from '@syncfusion/ej2-angular-buttons';
import { DropDownListAllModule } from '@syncfusion/ej2-angular-dropdowns';

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        TreeGridModule,
        ButtonModule,
        DropDownListAllModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [PageService,
                SortService,
                FilterService,
                ToolbarService]
})
export class AppModule { }
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app.module';

import 'zone.js';
enableProdMode();
platformBrowserDynamic().bootstrapModule(AppModule);

Customize sort icon

To customize the sort icon in the tree grid, you can override the default tree grid classes .e-icon-ascending and .e-icon-descending with custom content using CSS. Simply specify the desired icons or symbols using the content property as mentioned below

.e-treegrid .e-icon-ascending::before {
  content: '\e306';
}
	
.e-treegrid .e-icon-descending::before {
  content: '\e304';
}

In the below sample, tree grid is rendered with a customized sort icon.

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { sortData } from './datasource';

@Component({
  selector: 'app-container',
  encapsulation:ViewEncapsulation.None,
  template: `<ejs-treegrid [dataSource]='data' height='315' [treeColumnIndex]='1'  [allowSorting]='true' childMapping='subtasks' [sortSettings]='initialSort'>
                    <e-columns>
                        <e-column field='Category' headerText='Category' textAlign='Right' width=140></e-column>
                        <e-column field='orderName' headerText='Order Name' textAlign='Left' width=200></e-column>
                        <e-column field='orderDate' headerText='Order Date' textAlign='Right' format='yMd' width=150></e-column>
                        <e-column field='units' headerText='Units' textAlign='Right' width=80></e-column>
                    </e-columns>
                </ejs-treegrid>`,
  styleUrls:['sorting_style.css']
})
export class AppComponent implements OnInit {
  public data?: Object[];
  public initialSort?: Object;
  ngOnInit(): void {
    this.data = sortData;
    this.initialSort = {
      columns: [
        { field: 'Category', direction: 'Ascending' },
        { field: 'orderName', direction: 'Ascending' },
      ],
    };
  }
}
.e-treegrid .e-icon-ascending::before  {
    content: '\e306' !important;
  }
    
.e-treegrid .e-icon-descending::before {
    content: '\e304';
  }
import { NgModule,ViewChild } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { PageService, SortService, FilterService,ToolbarService,TreeGridModule } from '@syncfusion/ej2-angular-treegrid';
import { AppComponent } from './app.component';
import {ButtonModule} from '@syncfusion/ej2-angular-buttons';
import { DropDownListAllModule } from '@syncfusion/ej2-angular-dropdowns';

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        TreeGridModule,
        ButtonModule,
        DropDownListAllModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [PageService,
                SortService,
                FilterService,
                ToolbarService]
})
export class AppModule { }
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app.module';

import 'zone.js';
enableProdMode();
platformBrowserDynamic().bootstrapModule(AppModule);

Sort columns externally

The TreeGrid component in Syncfusion’s Angular suite allows you to customize the sorting of columns and provides flexibility in sorting based on external interactions. You can sort columns, remove a sort column, and clear sorting using an external button click.

Add sort columns

To sort a column externally, you can utilize the sortByColumn method with parameters columnName, direction and isMultiSort provided by the TreeGrid component. This method allows you to programmatically sort a specific column based on your requirements.

The following example demonstrates how to add sort columns to a tree grid. It utilizes the DropDownList component to select the column and sort direction. When an external button is clicked, the sortByColumn method is called with the specified columnName, direction, and isMultiSort parameters.

import { Component, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { DropDownListComponent } from '@syncfusion/ej2-angular-dropdowns';
import { TreeGridComponent } from '@syncfusion/ej2-angular-treegrid';
import { SortDirection } from '@syncfusion/ej2-grids';
import { sortData } from './datasource';

@Component({
  selector: 'app-container',
  template: `
            <div style="display: flex">
                <label style="padding: 30px 20px 0 0"> Column name :</label>
                <ejs-dropdownlist #dropdownColumn style="padding: 26px 0 0 0" index="0" width="120" [dataSource]="columns" [fields]="field"></ejs-dropdownlist>
            </div>
            <div style="display: flex">
                <label style="padding: 30px 17px 0 0"> Sorting direction :</label>
                <ejs-dropdownlist #dropdownDirection style="padding: 26px 0 0 0" index="0" width="120" [dataSource]="direction"></ejs-dropdownlist>
            </div>
            <button style="margin-top: 10px " ejs-button  id="button" cssClass="e-outline" (click)="addSortColumn()">Add sort column</button>
    
            <ejs-treegrid #treegrid [dataSource]='data' height='315' [treeColumnIndex]='1'  [allowSorting]='true' childMapping='subtasks' [sortSettings]='initialSort'>
                <e-columns>
                    <e-column field='Category' headerText='Category' textAlign='Right' width=140></e-column>
                    <e-column field='orderName' headerText='Order Name' textAlign='Left' width=200></e-column>
                    <e-column field='orderDate' headerText='Order Date' textAlign='Right' format='yMd' width=150></e-column>
                    <e-column field='units' headerText='Units' textAlign='Right' width=80></e-column>
                </e-columns>
            </ejs-treegrid>`,
})
export class AppComponent implements OnInit {
  public data?: Object[];
  public initialSort?: Object;

  @ViewChild('treegrid')
  public treegrid?: TreeGridComponent;
  @ViewChild('dropdownColumn')
  public dropDownColumn?: DropDownListComponent;
  @ViewChild('dropdownDirection')
  public dropDownDirection?: DropDownListComponent;
  public columns: object[] = [
    { text: 'Category', value: 'Category' },
    { text: 'Order Date', value: 'orderDate' },
    { text: 'Units', value: 'units' },
  ];
  public direction: object[] = [
    { text: 'Ascending', value: 'Ascending' },
    { text: 'Descending', value: 'Descending' },
  ];
  public field: object = { text: 'text', value: 'value' };

  ngOnInit(): void {
    this.data = sortData;
    this.initialSort = {
      columns: [{ field: 'orderName', direction: 'Ascending' }],
    };
  }
  addSortColumn() {
    (this.treegrid as TreeGridComponent).sortByColumn(
      (this.dropDownColumn as DropDownListComponent).value as SortDirection,
      (this.dropDownDirection as DropDownListComponent).value as SortDirection,
      true
    );
  }
}
import { NgModule,ViewChild } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { PageService, SortService, FilterService,ToolbarService,TreeGridModule } from '@syncfusion/ej2-angular-treegrid';
import { AppComponent } from './app.component';
import {ButtonModule} from '@syncfusion/ej2-angular-buttons';
import { DropDownListAllModule } from '@syncfusion/ej2-angular-dropdowns';

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        TreeGridModule,
        ButtonModule,
        DropDownListAllModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [PageService,
                SortService,
                FilterService,
                ToolbarService]
})
export class AppModule { }
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app.module';

import 'zone.js';
enableProdMode();
platformBrowserDynamic().bootstrapModule(AppModule);

Remove sort columns

To remove a sort column externally, you can use the removeSortColumn method provided by the TreeGrid component. This method allows you to remove the sorting applied to a specific column.

The following example demonstrates how to remove sort columns. It utilizes the DropDownList component to select the column. When an external button is clicked, the removeSortColumn method is called to remove the selected sort column.

import { Component, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { DropDownListComponent } from '@syncfusion/ej2-angular-dropdowns';
import { TreeGridComponent } from '@syncfusion/ej2-angular-treegrid';
import { SortDirection } from '@syncfusion/ej2-grids';
import { sortData } from './datasource';

@Component({
  selector: 'app-container',
  template: `
            <div style="display: flex">
                <label style="padding: 30px 20px 0 0"> Column name :</label>
                <ejs-dropdownlist #dropdown style="padding: 26px 0 0 0" index="0" width="120" [dataSource]="columns" [fields]="field"></ejs-dropdownlist>
            </div>
            <button style="margin-top: 10px " ejs-button id="button" cssClass="e-outline" (click)="removeSortColumn()" >Remove sort column</button>
    
            <ejs-treegrid #treegrid [dataSource]='data' height='315' [treeColumnIndex]='1'  [allowSorting]='true' childMapping='subtasks' [sortSettings]='initialSort'>
                <e-columns>
                    <e-column field='Category' headerText='Category' textAlign='Right' width=140></e-column>
                    <e-column field='orderName' headerText='Order Name' textAlign='Left' width=200></e-column>
                    <e-column field='orderDate' headerText='Order Date' textAlign='Right' format='yMd' width=150></e-column>
                    <e-column field='units' headerText='Units' textAlign='Right' width=80></e-column>
                </e-columns>
            </ejs-treegrid>`,
})
export class AppComponent implements OnInit {
  public data?: Object[];
  public initialSort?: Object;

  @ViewChild('treegrid')
  public treegrid?: TreeGridComponent;
  @ViewChild('dropdown')
  public dropDown?: DropDownListComponent;
  public columns: object[] = [
    { text: 'Category', value: 'Category' },
    { text: 'Order Name', value: 'orderName' },
    { text: 'Order Date', value: 'orderDate' },
    { text: 'Units', value: 'units' },
  ];
  public direction: object[] = [
    { text: 'Ascending', value: 'Ascending' },
    { text: 'Descending', value: 'Descending' },
  ];
  public field: object = { text: 'text', value: 'value' };

  ngOnInit(): void {
    this.data = sortData;
    this.initialSort = {
      columns: [
        { field: 'orderName', direction: 'Ascending' },
        { field: 'Category', direction: 'Descending' },
      ],
    };
  }

  removeSortColumn() {
    (this.treegrid as TreeGridComponent).removeSortColumn(
      (this.dropDown as DropDownListComponent).value as string
    );
  }
}
import { NgModule,ViewChild } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { PageService, SortService, FilterService,ToolbarService,TreeGridModule } from '@syncfusion/ej2-angular-treegrid';
import { AppComponent } from './app.component';
import {ButtonModule} from '@syncfusion/ej2-angular-buttons';
import { DropDownListAllModule } from '@syncfusion/ej2-angular-dropdowns';

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        TreeGridModule,
        ButtonModule,
        DropDownListAllModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [PageService,
                SortService,
                FilterService,
                ToolbarService]
})
export class AppModule { }
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app.module';

import 'zone.js';
enableProdMode();
platformBrowserDynamic().bootstrapModule(AppModule);

Clear sorting

To clear the sorting on an external button click, you can use the clearSorting method provided by the TreeGrid component. This method clears the sorting applied to all columns in the tree grid.

The following example demonstrates how to clear the sorting using clearSorting method in the external button click.

import { Component, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { TreeGridComponent } from '@syncfusion/ej2-angular-treegrid';
import { sortData } from './datasource';

@Component({
  selector: 'app-container',
  template: `
           <button ejs-button id="button" cssClass="e-outline" (click)="onExternalSort()"> Clear Sorting </button>
       
            <ejs-treegrid #treegrid [dataSource]='data' height='315' [treeColumnIndex]='1'  [allowSorting]='true' childMapping='subtasks' [sortSettings]='initialSort'>
                <e-columns>
                    <e-column field='Category' headerText='Category' textAlign='Right' width=140></e-column>
                    <e-column field='orderName' headerText='Order Name' textAlign='Left' width=200></e-column>
                    <e-column field='orderDate' headerText='Order Date' textAlign='Right' format='yMd' width=150></e-column>
                    <e-column field='units' headerText='Units' textAlign='Right' width=80></e-column>
                </e-columns>
            </ejs-treegrid>`,
})
export class AppComponent implements OnInit {
  public data?: Object[];
  public initialSort?: Object;

  @ViewChild('treegrid')
  public treegrid?: TreeGridComponent;

  ngOnInit(): void {
    this.data = sortData;
    this.initialSort = {
      columns: [
        { field: 'orderName', direction: 'Ascending' },
        { field: 'Category', direction: 'Descending' },
      ],
    };
  }

  onExternalSort() {
    (this.treegrid as TreeGridComponent).clearSorting();
  }
}
import { NgModule,ViewChild } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { PageService, SortService, FilterService,ToolbarService,TreeGridModule } from '@syncfusion/ej2-angular-treegrid';
import { AppComponent } from './app.component';
import {ButtonModule} from '@syncfusion/ej2-angular-buttons';
import { DropDownListAllModule } from '@syncfusion/ej2-angular-dropdowns';

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        TreeGridModule,
        ButtonModule,
        DropDownListAllModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [PageService,
                SortService,
                FilterService,
                ToolbarService]
})
export class AppModule { }
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app.module';

import 'zone.js';
enableProdMode();
platformBrowserDynamic().bootstrapModule(AppModule);

Sorting events

The TreeGrid component provides two events that are triggered during the sorting action such as actionBegin and actionComplete. These events can be used to perform any custom actions before and after the sorting action is completed.

  1. actionBegin: actionBegin event is triggered before the sorting action begins. It provides a way to perform any necessary operations before the sorting action takes place. This event provides a parameter that contains the current tree grid state, including the current sorting column, direction, and data.

  2. actionComplete: actionComplete event is triggered after the sorting action is completed. It provides a way to perform any necessary operations after the sorting action has taken place. This event provides a parameter that contains the current tree grid state, including the sorted data and column information.

The following example demonstrates how the actionBegin and actionComplete events work when sorting is performed. The actionBegin event is used to cancel the sorting of the Category column. The actionComplete event is used to display a message.

import { Component, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { TreeGridComponent } from '@syncfusion/ej2-angular-treegrid';
import { sortData } from './datasource';
import { SortEventArgs } from '@syncfusion/ej2-grids';

@Component({
  selector: 'app-container',
  template: `
          <div style="margin-left:100px;">
            <p style="color:red;" id="message"></p>
          </div>
       
            <ejs-treegrid #treegrid [dataSource]='data' height='315' [treeColumnIndex]='1'  [allowSorting]='true' childMapping='subtasks' (actionComplete)='actionComplete($event)' (actionBegin)='actionBegin($event)'>
                <e-columns>
                    <e-column field='Category' headerText='Category' textAlign='Right' width=140></e-column>
                    <e-column field='orderName' headerText='Order Name' textAlign='Left' width=200></e-column>
                    <e-column field='orderDate' headerText='Order Date' textAlign='Right' format='yMd' width=150></e-column>
                    <e-column field='units' headerText='Units' textAlign='Right' width=80></e-column>
                </e-columns>
            </ejs-treegrid>`,
})
export class AppComponent implements OnInit {
  public data?: Object[];
  public initialSort?: Object;
  public message?: string;

  @ViewChild('treegrid')
  public treegrid?: TreeGridComponent;

  ngOnInit(): void {
    this.data = sortData;
  }

  actionBegin(args: any) {
    if (args.requestType === 'sorting' && args.columnName === 'Category') {
      args.cancel = true;
      this.message = args.requestType + ' action cancelled for ' +  args.columnName + ' column';
    }
  }
  actionComplete({ requestType, columnName }: SortEventArgs) {
    this.message = requestType + ' action completed for ' + columnName + ' column';
  }
}
import { NgModule,ViewChild } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { PageService, SortService, FilterService,ToolbarService,TreeGridModule } from '@syncfusion/ej2-angular-treegrid';
import { AppComponent } from './app.component';
import {ButtonModule} from '@syncfusion/ej2-angular-buttons';
import { DropDownListAllModule } from '@syncfusion/ej2-angular-dropdowns';

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        TreeGridModule,
        ButtonModule,
        DropDownListAllModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [PageService,
                SortService,
                FilterService,
                ToolbarService]
})
export class AppModule { }
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app.module';

import 'zone.js';
enableProdMode();
platformBrowserDynamic().bootstrapModule(AppModule);

args.requestType refers to the current action being performed. For example in sorting, the args.requestType value is sorting.