javascript - Get Cell value after cell rendering applied to it ag-grid


Keywords:javascript 


Question: 

I am using ag-grid to display some information.

            var grid_column_definitions = [
                {
                    field: "id",
                    headerName: "ID",
                    cellRenderer: function (params) {
                        if (!params.data) return '';
                        return '<a ng-href="">{{data.id}}</a>';
                    }
                }
]

I know I can get the value of the cell using ag_grid api : (cell.node.data)

But this returns me the raw node. Is there a way where I can get the formatted row (html) after cell renderer has been applied to it.


1 Answer: 

OK, so I could not find any solution to get the contents from the template. But I was able to achieve this using different other ag-grid APIs. I needed this mostly to create the csv hyperlink of a column. eg. if cell a is hyperlink of www.example.com/cell_value, i wanted this to be there in csv as well as hyperlink.

So here is my solution:

scope.exportData = function(){ // function to export data, in case anyone need this.
  var params = {};
  var params.fileName = "test";
  params.processCellCallback = function(cell){
    return create_csv_link_based_on_column(cell);
  }
  scope.data.api.exportDataAsCsv(params);
}

===============

var create_csv_link_based_on_column(cell){
                var cellRenderer = cell.api.getColumnDef(cell.column.colId).cellRenderer; // get the cell renderer function
                if(cellRenderer){ // if the cell has cellRenderer functiond defined.
                    var cellTemplate = cellRenderer(cell.node); // eg. <a ng-href="">{{data.id}}</a>
                    if(cellTemplate){
                        if(cellTemplate.indexOf("href=") !== -1){ // if the template has hyperlink.
                            try{
                                var link = cellTemplate.split(/"/)[1]; // get the hyperlink. eg. 
                                var angularVariable = link.substring(link.lastIndexOf("{")+1,link.indexOf("}")); // eg. data.id
                                var properties = angularVariable.split('.'); // eg. ["data", "id"];
                                var propertyValue = properties.reduce((obj, prop) => obj && obj[prop], cell.node); // eg. cell.node.data.id = 16
                                var finalLink = link.replace("{{"+angularVariable+"}}", propertyValue); // replace angular variable with the data
                                finalLink = base_url + finalLink;
                                var csv_link = finalLink ? '=HYPERLINK("'+finalLink+'", "'+cell.value+'")' : cell.value;
                                return csv_link;
                            }catch(err){ // unexpected case
                                return cell.value;
                            }
                        }
                    }
                }
                return cell.value;
}