Search results

Render chart control based on cell selection in Angular Pivot Table component

18 May 2022 / 3 minutes to read

The cell selection support is enabled using the allowSelection property and its type and mode are configured using the selectionSettings property. The cellSelected event gets fired on every selection operation performed in the pivot table. This event returns the selected cell informations, like row header name, column header name, measure name, and value. Based on this information, the chart control will be plotted.

Source
Preview
app.component.ts
app.module.ts
Copied to clipboard
import { Component, ViewChild, OnInit } from '@angular/core';
import { IDataOptions, PivotView, IAxisSet, IFieldOptions, PivotViewComponent, FieldListService, PivotCellSelectedEventArgs } from '@syncfusion/ej2-angular-pivotview';
import { GridSettings } from '@syncfusion/ej2-pivotview/src/pivotview/model/gridsettings';
import { Chart, Category, Legend, Tooltip, ColumnSeries, LineSeries, SeriesModel } from '@syncfusion/ej2-charts';
import { renewableEnergy } from './datasource.ts';

@Component({
  selector: 'app-container',
  providers: [FieldListService],
  // specifies the template string for the pivot table component
  template: `<div><ejs-pivotview #pivotview id='PivotView' [dataSourceSettings]=dataSourceSettings showFieldList='true' width=width height=height [gridSettings]=gridSettings (cellSelected)="cellSelected($event)" (dataBound)="dataBound($event)"></ejs-pivotview><div><br/><div id="Chart"></div>`
})

export class AppComponent implements OnInit {

    public width: string;
    public height: number;
    public dataSourceSettings: IDataOptions;
    public gridSettings: GridSettings;
    public onInit: boolean = true;
    public measureList: { [key: string]: string } = {};
    public chart: Chart;
    public selectedCells: CellSelectedObject[];
    public chartSeries: SeriesModel[];

    @ViewChild('pivotview',{static: false})
    public pivotObj: PivotViewComponent;

    frameChartSeries(): SeriesModel[] {
        let columnGroupObject: { [key: string]: { x: string, y: number }[] } = {};
        for (let cell of this.selectedCells) {
        if (cell.measure !== '') {
            let columnSeries = (this.pivotObj.dataSourceSettings.values.length > 1 && this.measureList[cell.measure]) ?
            (cell.columnHeaders.toString() + ' ~ ' + this.measureList[cell.measure]) : cell.columnHeaders.toString();
            if (columnGroupObject[columnSeries]) {
            columnGroupObject[columnSeries].push({ x: cell.rowHeaders == '' ? 'Grand Total' : cell.rowHeaders.toString(), y: Number(cell.value) });
            } else {
            columnGroupObject[columnSeries] = [{ x: cell.rowHeaders == '' ? 'Grand Total' : cell.rowHeaders.toString(), y: Number(cell.value) }];
            }
        }
        }
        let columnKeys: string[] = Object.keys(columnGroupObject);
        let chartSeries: SeriesModel[] = [];
        for (let key of columnKeys) {
            chartSeries.push({
                dataSource: columnGroupObject[key],
                xName: 'x',
                yName: 'y',
                type: 'Column',
                name: key
            });
        }
        return chartSeries;
    }

    chartUpdate(): void {
        if (this.onInit) {
            this.onInit = false;
            Chart.Inject(ColumnSeries, LineSeries, Legend, Tooltip, Category);
            this.chart = new Chart({
                title: 'Sales Analysis',
                legendSettings: {
                    visible: true
                },
                tooltip: {
                    enable: true
                },
                primaryYAxis: {
                    title: this.pivotObj.dataSourceSettings.values.map(function (args) { return args.caption || args.name }).join(' ~ '),
                },
                primaryXAxis: {
                    valueType: 'Category',
                    title: this.pivotObj.dataSourceSettings.rows.map(function (args) { return args.caption || args.name }).join(' ~ '),
                    labelIntersectAction: 'Rotate45'
                },
                series: this.chartSeries,
            }, '#Chart');
        } else {
            this.chart.series = this.chartSeries;
            this.chart.primaryXAxis.title = this.pivotObj.dataSourceSettings.rows.map(function (args) { return args.caption || args.name }).join(' ~ ');
            this.chart.primaryYAxis.title = this.pivotObj.dataSourceSettings.values.map(function (args) { return args.caption || args.name }).join(' ~ ');
            this.chart.refresh();
        }
    }
    dataBound(): void {
        if(this.onInit) {
            for (let value of this.pivotObj.dataSourceSettings.values) {
                this.measureList[value.name] = value.caption || value.name;
            }
            this.pivotObj.grid.selectionModule.selectCellsByRange(
            { cellIndex: 1, rowIndex: 1 },
            { cellIndex: 3, rowIndex: 3 }
            );
        }
    }
    cellSelected(args: PivotCellSelectedEventArgs): void {
        this.selectedCells = args.selectedCellsInfo;
        if (this.selectedCells && this.selectedCells.length > 0) {
            this.chartSeries = this.frameChartSeries();
            this.chartUpdate();
        }
    }

    ngOnInit(): void {

        this.width = "100%";
        this.height = 350;

        this.gridSettings = {
            columnWidth: 120,
            allowSelection: true,
            selectionSettings: {
            mode: 'Cell',
            type: 'Multiple',
            cellSelectionMode: 'Box',
            }
        };

        this.dataSourceSettings = {
            dataSource: renewableEnergy,
            expandAll: true,
            enableSorting: true,
            drilledMembers: [{ name: 'Year', items: ['FY 2015', 'FY 2017', 'FY 2018'] }],
            formatSettings: [{ name: 'ProCost', format: 'C0' }],
            rows: [
                { name: 'Year', caption: 'Production Year' }
            ],
            columns: [
                { name: 'EnerType', caption: 'Energy Type' },
                { name: 'EneSource', caption: 'Energy Source' }
            ],
            values: [
                { name: 'ProCost', caption: 'Revenue Growth' }
            ],
            filters: []
        };
    }
 }
Copied to clipboard
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { PivotViewAllModule, PivotFieldListAllModule } from '@syncfusion/ej2-angular-pivotview';
import { AppComponent } from './app.component';

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        PivotViewAllModule,
        PivotFieldListAllModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent]
})
export class AppModule { }