My goal is to enable column sorting on cell data that includes custom HTML elements. I understand that I might need to create a custom function to override the default sorting behavior and refer it to the raw values instead of the rendered HTML output.
Despite consulting the ag-grid documentation at https://www.ag-grid.com/javascript-grid-sorting/, I am unable to find clear instructions on how to achieve this. The solution mentioned on the page seems relevant, but the explanation and sample code provided don't offer much help in understanding the implementation process. It appears that utilizing a comparator is necessary, yet in the example concerning dateComparator, it's unclear how the parameters (date1, date2) are utilized within the custom function.
Below, you can find some sample code demonstrating the issue, including a comparator function that gets called when clicking on the column header to sort the rows.
var columnDefs = [{ field: 'rank' }, { headerName: 'custom', cellRenderer: customCellRenderer, comparator: customNumberComparator }];
var rowData = [{ 'rank': 1, 'customData': '3.64' }, { 'rank': 2, 'customData': '-1.56' }, { 'rank': 3, 'customData': '11.21' }, { 'rank': 4, 'customData': '0.36' }, { 'rank': 5, 'customData': '45.1' }, { 'rank': 6, 'customData': '-34.2' }];
function customCellRenderer () {}
customCellRenderer.prototype.init = function ( params ) {
this.eGui = document.createElement ( 'span' );
this.eGui.textContent = params.data.customData + '%';
if ( parseFloat( params.data.customData ) < 0 ) {
this.eGui.setAttribute( 'style', 'color: red');
} else {
this.eGui.setAttribute( 'style', 'color: green');
}
}
customCellRenderer.prototype.getGui = function () {
return this.eGui;
}
// TEST FUNCTION TO OUTPUT params data
function customNumberComparator ( params ) {
const log = document.getElementById('log');
if (params === undefined ) {
log.textContent = 'undefined';
} else {
log.textContent = params.data;
}
}
var gridOptions = {
columnDefs: columnDefs,
rowData: rowData,
enableSorting: true
}
document.addEventListener("DOMContentLoaded", function() {
// lookup the container we want the Grid to use
var eGridDiv = document.querySelector('#myGrid');
// create the grid passing in the div to use together with the columns & data we want to use
new agGrid.Grid(eGridDiv, gridOptions);
}
<script src="https://unpkg.com/ag-grid/dist/ag-grid.min.js"></script>
<div id="myGrid" style="height: 150px;width:500px" class="ag-theme-fresh"></div>
<span id="log">customNumberComparator output here</span>