How to right align text in ag-grid for number

Viewed 16732

If any cell in ag-grid has numeric value like decimal, int or numeric i want that cell to be right aligned.

this.defaultColumnDefs = {
      width: 75,
      exportColumn: true,
      type: 'numericColumn',
      cellClass(params) {
        return params.colDef.type === 'numericColumn' ? 'ag-numeric-cell' : '';
      },
      filterParams: {
        buttons: ['clear'],
      },
      menuTabs: ['filterMenuTab'],
      filter: 'agTextColumnFilter',
      resizable: true,
      sortable: true
    };

It used to work before now i have to go to each column and specify the type. Why doesn't it take the default type?

3 Answers

There is an easy solution provided by Ag-grid documentation:

columnDefs: [
        { headerName: 'Column A', field: 'a' },
        { headerName: 'Column B', field: 'b', type: 'rightAligned' },
    ]

Just add type: 'rightAligned' property.

If you just want both the column header and cells to be right-aligned, you can use NicuVlad's answer:

columnDefs: [
        { headerName: 'Column A', field: 'a' },
        { headerName: 'Column B', field: 'b', type: 'rightAligned' },
    ]

However, if you just want the cells right-aligned and not the header:

columnDefs: [
        { headerName: 'Column A', field: 'a' },
        { headerName: 'Column B', field: 'b', cellClass: 'ag-right-aligned-cell' },
    ]

And if you want the header right-aligned and not the cells:

columnDefs: [
        { headerName: 'Column A', field: 'a' },
        { headerName: 'Column B', field: 'b', headerClass: 'ag-right-aligned-header' },
    ]

Fairly straightforward...

var colDef = {
    name: 'No. Field',
    field: 'noField',
    cellStyle: function(params) {
        if (typeof params.value === 'number') {
            return {text-align: 'right'};
        } else {
            return null;
        }
    }
}

You can go through your entire set of your ColumDefinitions (ColDef) any apply that cellstyle to all your columns programmatically.

By the by, this comes from the official documentation of ag-grid (albeit somewhat changed)

Related