Custom aggregate in Angular Grid component

19 Jan 20234 minutes to read

Sometimes you can have a scenario to calculate aggregate value using your own aggregate function, we can achieve this behavior using the custom aggregate option.
To use custom aggregation, specify the type as Custom and provide the custom aggregate function in the customAggregate property.

The custom aggregate function will be invoked with different arguments for Total and Group aggregations.

  • Total aggregation - the custom aggregate function will be called with whole data and the current AggregateColumn object.

  • Group aggregation - it will be called with current group details and the AggregateColumn object.

import { Component, OnInit } from '@angular/core';
import { data } from './datasource';
import { ReturnType } from '@syncfusion/ej2-grids';

@Component({
    selector: 'app-root',
    templateUrl: 'app/app.template.html'
})
export class AppComponent implements OnInit {

    public data: object[];
    public ShipCountry = 'ShipCountry';
    ngOnInit(): void {
        this.data = data;
    }
    public customAggregateFn = (sdata: ReturnType) =>
        sdata.result.filter((item: object) => item[this.ShipCountry] === 'Brazil').length
}
<ejs-grid [dataSource]='data' height='268px'>
    <e-columns>
        <e-column field='OrderID' headerText='Order ID' textAlign='right' width=120></e-column>
        <e-column field='CustomerID' headerText='Customer ID' width=150></e-column>
        <e-column field='Freight' format='C2' width=150></e-column>
        <e-column field='ShipCountry' headerText='Ship Country' width=150></e-column>
    </e-columns>
    <e-aggregates>
        <e-aggregate>
            <e-columns>
                <e-column columnName="ShipCountry" type="Custom" [customAggregate]="customAggregateFn">
                    <ng-template #footerTemplate let-data>Brazil Count: </ng-template>
                </e-column>
            </e-columns>
        </e-aggregate>
    </e-aggregates>
</ejs-grid>
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { GridModule } from '@syncfusion/ej2-angular-grids';
import { AggregateService } from '@syncfusion/ej2-angular-grids';
import { AppComponent } from './app.component';

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        GridModule
    ],
    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 template, use the key as Custom