Search code examples
ag-gridag-grid-ng2

How to format data before displaying it on ag-grid


I've just discovered ag-grid. I'm using it on angular2+ and loading data from api. One of fields is date, but its in ISO format. I've been trying to format it, is there any way to do it, is it possible to add pipe or some other way? Usually i do it like this {{ someISODate | date: 'dd.MM.yyyy HH:mm'}}. Do i really have to format it manually in component before displaying it? Also I was wondering if its possible to add two fields under one column. Why? Well i have column author, and in data that im getting from api i have author.firstname and author.lastname, and now I wanna display both fields in same column. Any hints or examples are more than welcomed.

columnDefs = [
    {headerName: 'Datum kreiranja', field: 'createdAt' }, //<-- wanna format it
    {headerName: 'Vrsta predmeta', field: 'type.name' },
    {headerName: 'Opis', field: 'description'},
    {headerName: 'Kontakt', field: 'client.name'},
    {headerName: 'Autor', field: 'author.firstname'}, //<-- wanna display author.lastname in same cell
    {headerName: 'Status', field: 'status.name'}
];

Solution

  • You can do this by using cellRenderer (or valueFormatter as pointed in the UPDATE) and moment library.

     {
          headerName: 'Datuk kreiranja', field: 'createdAt',
          cellRenderer: (data) => {
              return moment(data.value).format('MM/DD/YYYY HH:mm')
          }
     }
    

    If you don't want to use moment, then below is how you can do it.

    cellRenderer: (data) => {
         return data.value ? (new Date(data.value)).toLocaleDateString() : '';
    }
    

    For Author field as well,

    cellRenderer: (data) => {
         return data.author.firstname + ' ' + data.author.lastname;
    }
    

    Reference: ag-grid: Cell Rendering


    UPDATE

    As suggested by @Mariusz, using valueFormatter makes more sense in this scenario. As per documentation, Value Formatter vs Cell Renderer

    value formatter's are for text formatting and cell renderer's are for when you want to include HTML markup and potentially functionality to the cell. So for example, if you want to put punctuation into a value, use a value formatter, but if you want to put buttons or HTML links use a cell renderer.