Display the sum of a column that calculates the sum of rows, in the first cell of said column?

84 Views Asked by At

In ag-grid and Vue2 I have a column that sums its rows. The grid also adds two rows to the top: a totals row and a percentage row. The problem I'm facing is: displaying the sum of the totals column which is already using a valueGetter to display the sum of the rows.

Here is an example in Plunker: https://plnkr.co/edit/2HSVIY2APIyx622W?open=main.js&preview

It would seem that trying to access the rowData for the index 0 does not work, because actual rowData does not contain the sum of the rows (unless I'm missing something here).

valueGetter(params) {
    if (params.node.rowIndex === 0) {
    // Total column sum
    }
    if (params.node.rowIndex === 1) {
         return '100%'
    }
    
    // this calculates the rows sum
    if (params.node.rowIndex > 1) {
         const editableColumns = this.getEditableColumns();
         let total = 0;

         editableColumns.forEach((column) => {
          total += params.data[column];
         });

         return total;
    }
},
2

There are 2 best solutions below

0
On

I'm not familiar with Vue, but have done a lot development with ag-grid.

I think that your problem, a common one, is conceptual.

That is, you are attempting to use the grid as a data store.

Instead, I suggest that you keep all of your data, both server-provided and client-side calculated as application data (separate from the grid), and then use the grid only as as a user interface.

So, in your case, where the grid needs to display two calculated rows followed by some number of rows of server-provided data, the pattern would be to have the "rowData" array that you present to the grid actually have those two calculated rows as the first two entries in the array.

If you allow edits to the data via the grid, you would then update the calculated rows after each edit.

0
On

I needed to go deeper to get the desired result

Result:

Result

For this, I had to iterate over the editable columns when row index is 0 and get the column totals

      if (params.node.rowIndex === 0) {
        const nodes = params.api.getRenderedNodes();

        let columnTotal = 0;

        // Total column sum
        const editableColumns = this.getEditableColumns();
        let total = 0;

        editableColumns.forEach((column) => {
          console.log('column', column);
          console.log(params.data[column]);
          for (let i = 0; i < nodes.length; i++) {
            console.log('node', nodes[i]);
            if (nodes[i].id > 1) {
              columnTotal += nodes[i].data[column];
            }
          }
        });

        return columnTotal;
      }

Here's the working plunkr: https://plnkr.co/edit/ssypxwVcqm2nWqYV?preview