Column resizing in Angular TreeGrid component

2 Mar 202424 minutes to read

TreeGrid component provides an intuitive user interface for resizing columns to fit their content. This feature allows users to easily adjust the width of the columns to improve readability and aesthetics of the data presented. To enable column resizing, set the allowResizing property of the tree grid to true.

Once column resizing is enabled, columns width can be resized by clicking and dragging at the right edge of the column header. While dragging the column, the width of the respective column will be resized immediately.

To use the column resize, inject ResizeService in the provider section of AppModule.

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

@Component({
    selector: 'app-container',
    template: `<ejs-treegrid #treegrid [dataSource]='data' height='250' [allowResizing]='true' (dataBound)='onDataBound()' [treeColumnIndex]='1' childMapping='subtasks' >
                    <e-columns>
                        <e-column field='taskID' headerText='Task ID' textAlign='Right' width=90></e-column>
                        <e-column field='taskName' headerText='Task Name' textAlign='Left' width=180></e-column>
                        <e-column field='startDate' headerText='Start Date' textAlign='Right' format='yMd' width=120></e-column>
                        <e-column field='duration' headerText='Duration' textAlign='Right' width=130></e-column>
                        <e-column field='progress' headerText='Progress' textAlign='Right' width=120></e-column>
                    </e-columns>
                </ejs-treegrid>`,
    providers: [ResizeService ]
})
export class AppComponent implements OnInit {

    public data?: Object[];
    @ViewChild('treegrid')
    public treeGridObj?: TreeGridComponent;

    ngOnInit(): void {
        this.data = sampleData;
    }
    onDataBound() {
            (this.treeGridObj as TreeGridComponent).autoFitColumns(['taskName']);
    }
}
import { NgModule,ViewChild } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { TreeGridModule } from '@syncfusion/ej2-angular-treegrid';
import { PageService, SortService, FilterService } from '@syncfusion/ej2-angular-treegrid';
import { AppComponent } from './app.component';
import {ButtonModule} from '@syncfusion/ej2-angular-buttons';

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        TreeGridModule,
        ButtonModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [PageService,
                SortService,
                FilterService]
})
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);

  • You can disable resizing for a particular column, by specifying columns.allowResizing to false.
  • In RTL mode, you can click and drag the left edge of header cell to resize the column.
  • The width property of the column can be set initially to define the default width of the column. However, when column resizing is enabled, you can override the default width by manually resizing the columns.

Restrict the resizing based on minimum and maximum width

The TreeGrid component allows you to restrict the column width resizing between a minimum and maximum width. This can be useful when you want to ensure that your tree grid’s columns stay within a certain range of sizes.

To enable this feature, you can define the columns.minWidth and columns.maxWidth properties of the columns directive for the respective column.

In the below code, TaskName and duration columns are defined with minimum and maximum width. The TaskName column is set to have a minimum width of 170 pixels and a maximum width of 250 pixels. Similarly, the duration column is set to have a minimum width of 50 pixels and a maximum width of 150 pixels.

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

@Component({
    selector: 'app-container',
    template: `<ejs-treegrid #treegrid [dataSource]='data' height='250' [allowResizing]='true' [treeColumnIndex]='1' childMapping='subtasks' >
                    <e-columns>
                        <e-column field='taskID' headerText='Task ID' textAlign='Right' width=90></e-column>
                        <e-column field='taskName' headerText='Task Name' minWidth=170 maxWidth=250 textAlign='Left' width=180></e-column>
                        <e-column field='startDate' headerText='Start Date' textAlign='Right' format='yMd' width=90></e-column>
                        <e-column field='duration' headerText='Duration' minWidth=50 maxWidth=150 textAlign='Right' width=80></e-column>
                        <e-column field='progress' headerText='Progress' textAlign='Right' width=120></e-column>
                    </e-columns>
                </ejs-treegrid>`,
    providers: [ResizeService ]
})
export class AppComponent implements OnInit {

    public data?: Object[];

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

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        TreeGridModule,
        ButtonModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [PageService,
                SortService,
                FilterService]
})
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 resizing for particular column

The TreeGrid component provides the ability to prevent resizing for a particular column. This can be useful if you want to maintain a consistent column width or prevent users from changing the width of a column.

You can disable resizing for a particular column by setting the allowResizing property of the column to false. The following example demonstrates, how to disabled resize for Task Name column.

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

@Component({
    selector: 'app-container',
    template: `<ejs-treegrid #treegrid [dataSource]='data' height='250' [allowResizing]='true' [treeColumnIndex]='1' childMapping='subtasks' >
                    <e-columns>
                        <e-column field='taskID' headerText='Task ID' textAlign='Right' width=90></e-column>
                        <e-column field='taskName' headerText='Task Name' textAlign='Left' [allowResizing]="false" width=180></e-column>
                        <e-column field='startDate' headerText='Start Date' textAlign='Right' format='yMd' width=90></e-column>
                        <e-column field='duration' headerText='Duration' textAlign='Right' width=80></e-column>
                        <e-column field='progress' headerText='Progress' textAlign='Right' width=120></e-column>
                    </e-columns>
                </ejs-treegrid>`,
    providers: [ResizeService ]
})
export class AppComponent implements OnInit {

    public data?: Object[];

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

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        TreeGridModule,
        ButtonModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [PageService,
                SortService,
                FilterService]
})
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);

You can also prevent resizing by setting args.cancel to true in the resizeStart event.

Resize stacked header column

TreeGrid component allows to resize stacked columns by clicking and dragging the right edge of the stacked column header. During the resizing action, the width of the child columns is resized at the same time. You can disable resize for any particular stacked column by setting allowResizing as false to its columns.

In this below code, we have disabled resize for Shipped Date column.

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

@Component({
    selector: 'app-container',
    template: `<ejs-treegrid #treegrid [dataSource]='data' childMapping='subtasks' height='260' [allowResizing]='true' [treeColumnIndex]='1' >
                    <e-columns>
                        <e-column headerText='Order Details' [columns]='orderColumns'></e-column>
                        <e-column headerText='Shipment Details' [columns]='shipColumns'></e-column>
                        <e-column headerText='Price Details' [columns]='priceColumns'></e-column>
                    </e-columns>
                </ejs-treegrid>`,
    providers: [ResizeService ]
})
export class AppComponent implements OnInit {

    public data?: Object[];
    public orderColumns?: Object[];
    public shipColumns?: Object[];
    public priceColumns?: Object[];

    ngOnInit(): void {
        this.data = stackedData;
        this.orderColumns = [
            { field: 'orderID', headerText: 'Order ID', textAlign: 'Right', width: 90 },
            { field: 'orderName', headerText: 'Order Name', textAlign: 'Left', width: 180 },
            { field: 'orderDate', headerText: 'Order Date', textAlign: 'Right', width: 120, format: 'yMd'}
        ];
        this.shipColumns = [
            { field: 'shipMentCategory', headerText: 'Shipment Category', textAlign: 'Left', width: 150 },
            { field: 'shippedDate', headerText: 'Shipped Date', textAlign: 'Right', width: 120, format: 'yMd' , allowResizing: false},
            { field: 'units', headerText: 'Units', textAlign: 'Right', width: 90 }
        ];
        this.priceColumns = [
            { field: 'unitPrice', headerText: 'Price per unit', format: 'c2', type: 'number', width: 120, textAlign: 'Right' },
            { field: 'price', headerText: 'Total Price', width: 110, format: 'c2', type: 'number', textAlign: 'Right' }
        ];
    }
}
import { NgModule,ViewChild } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { TreeGridModule } from '@syncfusion/ej2-angular-treegrid';
import { PageService, SortService, FilterService } from '@syncfusion/ej2-angular-treegrid';
import { AppComponent } from './app.component';
import {ButtonModule} from '@syncfusion/ej2-angular-buttons';

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        TreeGridModule,
        ButtonModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [PageService,
                SortService,
                FilterService]
})
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);

Resizing modes

You can resizing the column with different mode in treegrid by using the ResizeMode property of grid. In Grid component have a ResizeSettingsModel interface for configuring the resizing behavior of grid columns. The interface includes a property named mode which is of the type ResizeMode. The ResizeMode is an enum that determines the available resizing modes for the grid columns. There are two resizing modes available for grid columns in Grid:

  1. Normal Mode: This mode does not adjust the columns to fit the remaining space. When the sum of column width is less than the grid’s width, empty space will be present to the right of the last column. When the sum of column width is greater than the grid’s width, columns will overflow, and a horizontal scrollbar will appear.

  2. Auto Mode: This mode automatically resizes the columns to fill the remaining space. When the sum of column width is less than the grid’s width, the columns will be automatically expanded to fill the empty space. Conversely, when the sum of column width is greater than the grid’s width, the columns will be automatically contracted to fit within the available space.

You can use this feature through grid property object of tree grid instance in load event.

The following example demonstrates how to set the resizeSettings.mode property to Normal and Auto on changing the dropdown value using the change event of the DropDownList component.

import { Component, OnInit,ViewChild } from '@angular/core';
import { sampleData } from './datasource';
import {  ResizeMode } from '@syncfusion/ej2-angular-grids';
import { ChangeEventArgs } from '@syncfusion/ej2-angular-dropdowns';
import { ResizeService,TreeGridComponent  } from '@syncfusion/ej2-angular-treegrid';

@Component({
    selector: 'app-container',
    template: `<div style="display: flex">
                   <label style="padding: 10px 10px 26px 0"> Change the resize mode: </label>
                   <ejs-dropdownlist style="margin-top:5px" index="0" width="150" [dataSource]="ddlData"
                   (change)="valueChange($event)"></ejs-dropdownlist>
                </div>

                <ejs-treegrid #treegrid [dataSource]='data' height='250' [allowResizing]='true' [treeColumnIndex]='1' childMapping='subtasks'>
                    <e-columns>
                        <e-column field='taskID' headerText='Task ID' textAlign='Right' width=90></e-column>
                        <e-column field='taskName' headerText='Task Name' textAlign='Left' width=180></e-column>
                        <e-column field='startDate' headerText='Start Date' textAlign='Right' format='yMd' width=90></e-column>
                        <e-column field='duration' headerText='Duration' textAlign='Right' width=80></e-column>
                        <e-column field='progress' headerText='Progress' textAlign='Right' width=120></e-column>
                    </e-columns>
                </ejs-treegrid>`
})
export class AppComponent implements OnInit {

    public data?: object[];
    @ViewChild('treegrid')
    public treegrid?: TreeGridComponent;
    public ddlData: object[] = [
      { text: 'Normal', value: 'Normal' },
      { text: 'Auto', value: 'Auto' },
    ];
    ngOnInit(): void { 
        this.data = sampleData;
    }

    valueChange(args: ChangeEventArgs): void {
        (this.treegrid as TreeGridComponent).grid.resizeSettings.mode = (args.value as ResizeMode);
      }
}
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { TreeGridModule, ResizeService } from '@syncfusion/ej2-angular-treegrid';
import { DropDownListAllModule } from '@syncfusion/ej2-angular-dropdowns';
import { AppComponent } from './app.component';

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        TreeGridModule,DropDownListAllModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [ResizeService]
})
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);

When the autoFit property is set to true, the tree grid will automatically adjust its column width based on the content inside them. In normal resize mode, if the autoFit property is set to true, the tree grid will maintain any empty space that is left over after resizing the columns. However, in auto resize mode, the tree grid will ignore any empty space.

Touch interaction

TreeGrid component provides support for touch interactions to enable users to interact with the tree grid using their mobile devices. Users can resize columns in the tree grid by tapping and dragging the floating handler, and can also use the column menu to autofit columns.

Resizing Columns on Touch Devices

To resize columns on a touch device:

1.Tap on the right edge of the header cell of the column that you want to resize.

2.A floating handler will appear over the right border of the column.

3.Tap and drag the floating handler to resize the column to the desired width.

The following screenshot represents the column resizing on the touch device.

Touch interaction image

Resizing column externally

TreeGrid component provides the ability to resize columns using an external button click. This can be achieved by changing the width property of the column and refreshing the tree grid using the refreshColumns method in the external button click function.

The following example demonstrates how to resize the columns in a tree grid. This is done by using the change event of the DropDownList component by change the width property of the selected column. This is accomplished using the getColumnByField on external button click. Then, the refreshColumns method is called on the TreeGrid component to update the displayed columns based on user interaction.

import { Component, OnInit,ViewChild } from '@angular/core';
import { sampleData } from './datasource';
import {  ResizeMode } from '@syncfusion/ej2-angular-grids';
import { ChangeEventArgs } from '@syncfusion/ej2-angular-dropdowns';
import { ResizeService,TreeGridComponent  } from '@syncfusion/ej2-angular-treegrid';
import { DropDownListComponent } from '@syncfusion/ej2-angular-dropdowns';

@Component({
    selector: 'app-container',
    template: `<div style="display:flex;">
                <label style="padding: 10px 10px 26px 0">Change the field: </label>
                 <ejs-dropdownlist style="margin-top:5px" id="value" #dropdown index="0" width="120"
                  [fields]="field" [dataSource]="ddlData"></ejs-dropdownlist>
               </div>

               <div>
                <label style="padding: 30px 17px 0 0">Enter the width: </label>
                  <ejs-textbox #textbox required placeholder="Enter new width" width="120"></ejs-textbox>
                  <button ejs-button id="button" cssClass="e-outline" (click)="onExternalResize()">Resize</button>
               </div>    

              <ejs-treegrid #treegrid [dataSource]='data' height='250' [allowResizing]='true' [treeColumnIndex]='1' childMapping='subtasks'>
                    <e-columns>
                        <e-column field='taskID' headerText='Task ID' textAlign='Right' width=90></e-column>
                        <e-column field='taskName' headerText='Task Name' textAlign='Left' width=180></e-column>
                        <e-column field='startDate' headerText='Start Date' textAlign='Right' format='yMd' width=90></e-column>
                        <e-column field='duration' headerText='Duration' textAlign='Right' width=80></e-column>
                        <e-column field='progress' headerText='Progress' textAlign='Right' width=120></e-column>
                    </e-columns>
              </ejs-treegrid>`
})
export class AppComponent implements OnInit {

    public data?: object[];
    public field: object = { text: 'text', value: 'value' };
    @ViewChild('treegrid')
    public treegrid?: TreeGridComponent;
    @ViewChild('dropdown')
    public dropDown?: DropDownListComponent;
    @ViewChild('textbox')
    public textbox?: any;

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

   public ddlData: object[] = [
    { text: 'taskID', value: 'taskID' },
    { text: 'taskName', value: 'taskName' },
    { text: 'startDate', value: 'startDate' },
    { text: 'duration', value: 'duration' },
    { text: 'progress', value: 'progress' },
  ];
  onExternalResize() {
    (this.treegrid as TreeGridComponent).getColumnByField((this.dropDown as DropDownListComponent).value as string).width = this.textbox.element.value;
    (this.treegrid as TreeGridComponent).refreshColumns();
  }
}
import { NgModule,ViewChild } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { TreeGridModule } from '@syncfusion/ej2-angular-treegrid';
import { PageService, SortService, FilterService,ResizeService } from '@syncfusion/ej2-angular-treegrid';
import { AppComponent } from './app.component';
import {ButtonModule} from '@syncfusion/ej2-angular-buttons';
import {TextBoxModule} from '@syncfusion/ej2-angular-inputs';
import {DropDownListModule} from '@syncfusion/ej2-angular-dropdowns';
/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        TreeGridModule,
        ButtonModule,TextBoxModule,DropDownListModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [PageService,
                SortService,
                FilterService,ResizeService]
})
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 refreshColumns method is used to refresh the tree grid after the column widths are updated. Column resizing externally is useful when you want to provide a custom interface to the user for resizing columns.

Resizing events

During the resizing action, the TreeGrid component triggers the below three events.

1.The resizeStart event triggers when column resize starts. This event can be used to perform actions when the user begins to resize a column.

2.The resizing event triggers when column header element is dragged (moved) continuously. This event is useful when you want to perform certain actions during the column resize process.

3.The resizeStop event triggers when column resize ends. This event can be used to perform actions after the column is resized.

The following is an example of using the resizing events, the resizeStart event is used to cancel the resizing of the taskID column. The resizeStop event is used to apply custom CSS attributes to the resized column.

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

@Component({
    selector: 'app-container',
    template: `<div style="margin-left:180px"><p style="color:red;" id="message"></p></div>
          
                <ejs-treegrid #treegrid [dataSource]='data' height='250' [allowResizing]='true' [treeColumnIndex]='1' childMapping='subtasks' 
                (resizeStart)="resizeStart()" (resizing)="resizing()" (resizeStop)="resizeStop()">
                    <e-columns>
                        <e-column field='taskID' headerText='Task ID' textAlign='Right' width=90></e-column>
                        <e-column field='taskName' headerText='Task Name' minWidth=170 maxWidth=250 textAlign='Left' width=180></e-column>
                        <e-column field='startDate' headerText='Start Date' textAlign='Right' format='yMd' width=90></e-column>
                        <e-column field='duration' headerText='Duration' minWidth=50 maxWidth=150 textAlign='Right' width=80></e-column>
                        <e-column field='progress' headerText='Progress' textAlign='Right' width=120></e-column>
                    </e-columns>
                </ejs-treegrid>`
})
export class AppComponent implements OnInit {

    public data?: object[];
    public message?: string;

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

    resizing() {
        this.message = 'resizing event is Triggered';
    }
    resizeStop() {
        this.message = 'resizeStop event is Triggered';
    }
    resizeStart() {
        this.message = 'resizeStart event is Triggered';
    }
}
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { TreeGridModule, ResizeService } from '@syncfusion/ej2-angular-treegrid';
import { AppComponent } from './app.component';

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        TreeGridModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [ResizeService]
})
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 ResizeArgs object passed to the events contains information such as the current column width, new column width, column index, and the original event. The resizing event is triggered multiple times during a single resize operation, so be careful when performing heavy operations in this event.