12

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.

CodeChanger
  • 7,953
  • 5
  • 49
  • 80

3 Answers3

25

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.

Audwin Oyong
  • 2,247
  • 3
  • 15
  • 32
CodeChanger
  • 7,953
  • 5
  • 49
  • 80
1

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/

taltaltal
  • 21
  • 1
  • 4
  • 2
    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](/help/how-to-answer). – Adam Jaamour Oct 25 '21 at 15:00
  • 1
    @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. – Eliezer Berlin Nov 25 '21 at 09:52
  • 3
    This built-in functionality is for the paid Enterprise version only – Piers Geyman Mar 17 '22 at 19:43
0

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>