Search results

Custom Aggregate in Angular Grid component

30 Sep 2022 / 1 minute 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.
Source
Preview
app.component.ts
app.template.html
app.module.ts
main.ts
Copied to clipboard
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
}
Copied to clipboard
<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: {{data.Custom}}</ng-template>
                </e-column>
            </e-columns>
        </e-aggregate>
    </e-aggregates>
</ejs-grid>
Copied to clipboard
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 { }
Copied to clipboard
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