Search code examples
reactjsformattingag-gridag-grid-react

Ag Grid partial cell formatting - e.g. how to have some text in a cell styled - bold, italic, colored (but not other text)


In a simple HTML table, if I want to apply text formatting to a portion in a cell, such as:

<td>Qty: <b>5</b></td>

It's very simple to make part of the text bold, and part of it not. I've looked through a bunch of Ag Grid docs, and I'm not seeing a simple way to do that. (I'd prefer not to need a cell renderer component for this; just a simple method using a value-formatter.)

Here's some of what I've looked at, but it doesn't provide such:

https://www.ag-grid.com/javascript-data-grid/cell-content/

https://blog.ag-grid.com/conditional-formatting-for-cells-in-ag-grid/

https://www.ag-grid.com/javascript-data-grid/value-formatters/

I'm hoping there's a way like:

valueFormatter(params) {
   return 'Qty: <b>' + params.value + '</b>';
},

But I've tried that, and it doesn't interpret/format using the HTML tags.


Solution

  • I found a way to do this; it uses the cellRenderer, but does not require a separate component - it can be defined directly from the columnDefs:

      {
        field: 'ItemID',
        headerName: 'Item ID',
        cellRenderer: params => `<b>ID:</b> ${params.data.ItemID}`,
      },
    

    Example

    This lets you provide minor selective formatting directly within the columnDefs, without needing to create a separate relatively mundane component for each field. Makes the code shorter, faster to write, and easier to maintain.