Custom aggregate in Angular Treegrid component

17 Nov 20224 minutes to read

To calculate the aggregate value with your own aggregate functions, use the custom aggregate option. To use custom aggregation, specify the type as Custom, and provide the custom aggregate function in the customAggregate property.

import { Component, OnInit } from '@angular/core';
import { summaryData } from './datasource';
import { getObject, CustomSummaryType } from '@syncfusion/ej2-grids';
@Component({
    selector: 'app-container',
    template: `<ejs-treegrid [dataSource]='data' height='245' [treeColumnIndex]='0'  childMapping='subtasks' >
        <e-columns>
                   <e-column field='category' headerText='Category'  width=240></e-column>
                   <e-column field='units' headerText='Total Units'  textAlign='Right' type='number' Width=130></e-column>
                   <e-column field='unitPrice' headerText='Unit Price($)' format='C2' textAlign='Right' type='number' width=110 ></e-column>
                   <e-column field='price' headerText='Price($)' textAlign='Right' type='number' width=160 ></e-column>
        </e-columns>
        <e-aggregates >
        <e-aggregate [showChildSummary]='false' >
            <e-columns>
                <e-column field="price" format='C2' type="Custom" [customAggregate]='customAggregateFn' columnName='category' >
                    <ng-template #footerTemplate let-data>Count of Frozen seafood : </ng-template>
                </e-column>
            </e-columns>
        </e-aggregate>
    </e-aggregates>
                </ejs-treegrid>`
})
export class AppComponent implements OnInit {

    public data: Object[];
    ngOnInit(): void {
        this.data = summaryData;
    }
    customAggregateFn (data: Object): number {
        let sampleData: Object[] = getObject('result', data);
        let countLength: number; countLength = 0;
        sampleData.filter((item: Object) => {
            let data: string = getObject('category', item);
            if (data === 'Frozen seafood') {
                countLength++;
            }
        });
        return countLength;
    };
}
import { NgModule,ViewChild } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { TreeGridModule } from '@syncfusion/ej2-angular-treegrid';
import { AggregateService  } from '@syncfusion/ej2-angular-treegrid';
import { AppComponent } from './app.component';

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

enableProdMode();
platformBrowserDynamic().bootstrapModule(AppModule);

To access the custom aggregate value inside the template, use the key as Custom.