How to enable or show total row in footer of ag-grid table
Asked Answered
M

3

13

I am working with Ag-Grid table and I want to show the total row in the footer of the table. Some How I achieved it by using 2 tables 1 is for actual data and 2nd is for the Total row.

It's working fine with a Normal non-scrollable table but if it's a pined or scrollable table then the top table scrolls but the bottom one sticks in the same place.

I want to scroll both the table at the same time with the same offset.

For more detail look at the below screenshot which I have the total bottom table.

Normal Table:

enter image description here

You can see in the normal table it's showing total perfectly.

While in the Pinned column table it's not working as expected.

Pinned Column Table: enter image description here

Look at the scroll bar of both the table.

I want to scroll both the table parallelly.

Or is there any other way to show the Total row other than the dual table?

Please Guide me on this.

Mayce answered 7/12, 2020 at 6:53 Comment(3)
could you provide a stackblitz or a plunker of your issue please.Adoration
Ya sure will add it soon.Mayce
Hey, @Viqas thanks for your interest fortunately I found the solution in a different way please look at my answer posted here and give ur valuable comments on that.Mayce
M
29

Finally, after lots of R&D on the footer total row, I found that we can implement PinnedBottomRow to show our total for the table.

So I dropped the above idea as it's creating a problem with the pinned columns and also managing 2 tables is tricky.

Thanks to AreYouSiries who provided such a nice demo on plucker here

Also Thanks to Ag-Grid for such a nice doc with live examples

My Custom Plucker version for Total Row is here

By following the above examples I am able to achieve my exact requirements and now it's working as expected.

Let me add sort steps to achieve the total row feature in ag-grid:

1st step - Generate Pinned Total Row: Below function will generate an empty target object with all your columns available in the grid.

generatePinnedBottomData(){
    // generate a row-data with null values
    let result = {};

    this.gridColumnApi.getAllGridColumns().forEach(item => {
        result[item.colId] = null;
    });
    return this.calculatePinnedBottomData(result);
}

2nd step Calculate Total for some or all the columns: You need to calculate the total from row data and set the value in the above generated targeted row.

calculatePinnedBottomData(target: any){
        //console.log(target);
        //**list of columns fo aggregation**
        let columnsWithAggregation = ['age']
        columnsWithAggregation.forEach(element => {
          console.log('element', element);
            this.gridApi.forEachNodeAfterFilter((rowNode: RowNode) => {
              //if(rowNode.index < 10){
                //console.log(rowNode);
              //}
                if (rowNode.data[element])
                    target[element] += Number(rowNode.data[element].toFixed(2));
            });
            if (target[element])
                target[element] = `Age Sum: ${target[element].toFixed(2)}`;
        })
        //console.log(target);
        return target;
    }

3rd and last step: Call above generatePinnedBottomData() function where u get your grid data from API or local DB. In the above example, we used to call from onGridReady()

onGridReady(params) {
    this.gridApi = params.api;
    this.gridColumnApi = params.columnApi;
    console.log(this.gridColumnApi.getAllGridColumns())
    this.http
      .get("https://raw.githubusercontent.com/ag-grid/ag-grid/master/packages/ag-grid-docs/src/olympicWinners.json")
      .subscribe(data => {
        this.rowData = data;
        setTimeout(()=>{
          let pinnedBottomData = this.generatePinnedBottomData();
        this.gridApi.setPinnedBottomRowData([pinnedBottomData]);
        }, 500)
      });
  }

You need to assign generated data to the grid.

That's it now you can see your total row pinned at bottom of the grid.

Final Output: enter image description here

Hope my post will help you to achieve the total row in the grid.

Mayce answered 8/12, 2020 at 12:36 Comment(2)
Looks great! It doesn't change depending on the current filters, but that should be relatively simple to fix.Sheehan
From the latest AG Grid debug output: setPinnedBottomRowData is deprecated. Please use 'api.setGridOption('pinnedBottomRowData', newValue)' or 'api.updateGridOptions({ pinnedBottomRowData: newValue })' instead. Works the same though.Rotator
B
2

Ag-Grid has a built-in option to create a group footer that uses aggregation functions such as sum, avg, and more. See details here: https://www.ag-grid.com/javascript-data-grid/grouping-footers/

Bedridden answered 25/10, 2021 at 14:9 Comment(4)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Parhelion
@AdamJaamour FYI, for people familiar with this library, this answer was very useful. Although of course it could definitely have benefited from from some sample code or a JSFiddle.Sheehan
This built-in functionality is for the paid Enterprise version onlyApo
Is it possible to have a footer row using a separate aggregation method to the table? i.e I want the table to show avg but the footer row to be the sum of avg.Jovi
E
2

Here is a example to add a pinned total row. Hope it helps anyone looking for it.

const columnDefs = [
  { field: "make" },
  { field: "model" },
  { field: "price" }
];

// specify the data
const rowData = [
  { make: "Toyota", model: "Celica", price: 35000 },
  { make: "Ford", model: "Mondeo", price: 32000 },
  { make: "Porsche", model: "Boxster", price: 72000 }
];

const calcTotalCols = ['price'];

const totalRow = function(api) {
    let result = [{}];
    // initialize all total columns to zero
    calcTotalCols.forEach(function (params){
        result[0][params] = 0
    });
   // calculate all total columns
    calcTotalCols.forEach(function (params){
        rowData.forEach(function (line) {
            result[0][params] += line[params];
        });
    });
    api.setPinnedBottomRowData(result);
}
// let the grid know which columns and what data to use
const gridOptions = {
  columnDefs: columnDefs,
  rowData: rowData
};

// setup the grid after the page has finished loading
document.addEventListener('DOMContentLoaded', () => {
    const gridDiv = document.querySelector('#myGrid');
    new agGrid.Grid(gridDiv, gridOptions);
    totalRow(gridOptions.api);
});
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Ag-Grid Total Row Example</title>
    <script src="https://unpkg.com/ag-grid-community/dist/ag-grid-community.min.js"></script>
    <script src="main.js"></script>
</head>
<body>
    <div id="myGrid" style="height: 200px; width:500px;" class="ag-theme-alpine"></div>
</body>
</html>
Earlearla answered 24/8, 2022 at 5:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.