Using ng-template as cellRenderer in ag-grid / Angular 5


Keywords:angular 


Question: 

It would seem that whenever you want to customize the output of the cell by something more than just text transformation, you need a cellRenderer. But it requires a whole new component to fulfill that goal. That approach is, in general, fine, but I've found that in my project I'm using grids a lot, and I need custom cell renderers for them. Most of the time they are also not re-usable and specific to particular grid. The overhead for creating (and storing somewhere in the filesystem) another component, just for the sake of providing an HTML template structure, seems a bit overkill to me.

Is there a way to render a cell in Ag-Grid, without specifying a full-blown component, inheriting from AgGrid renderers? For instance, can I just use ng-template with #id reference, that I could pass somehow to Ag-Grid?


1 Answer: 

But it requires a whole new component to fulfil that goal.

That's not true everytime.


without specifying a full-blown component, inheriting from AgGrid renderers? For instance, can I just use ng-template with #id reference, that I could pass somehow to Ag-Grid?

Yes, it's possible.


Not sure about ng-template, but surely you can provide a function as cellRenderer which returns HTML string or DOM element.

Check the documentation: ag-grid Cell Rendering

There are actually 4 ways

The cell editor for a column is set via colDef.cellRenderer and can be any of the following types:

  1. undefined / null: Grid renders the value as a string.
  2. String: The name of a cell renderer registered with the grid.
  3. Class: Provide your own cell renderer component directly without registering.
  4. Function: A function that returns either an HTML string or DOM element for display.
 // Function - A function that returns an HTML string or DOM element for display
 column.cellRenderer = function(params) {
     // put the value in bold
     return 'Value is <b>'+params.value+'</b>';
 }