How to show row number as the first column?
Asked Answered
K

3

15

It's like this (but start from 1):

enter image description here

Please note the number is for the row element of grid instead of row data of the source. So the number shown in the first cell of each rows should indicate the position of the current row (which starts from 1 for the first row) regardless the row data and the sorting criteria.

Update: The result is like this: https://jsfiddle.net/wp6o350z/

<script src="https://unpkg.com/ag-grid/dist/ag-grid.min.noStyle.js"></script>
<link rel="stylesheet" href="https://unpkg.com/ag-grid/dist/styles/ag-grid.css">
<link rel="stylesheet" href="https://unpkg.com/ag-grid/dist/styles/ag-theme-balham.css">

<div id="myGrid" style="height: 200px;width:500px;" class="ag-theme-balham"></div>

<script type="text/javascript" charset="utf-8">
    // specify the columns
    var columnDefs = [
      {headerName: "#", field: "row", width: 30 },
      {headerName: "Make", field: "make", width: 100 },
      {headerName: "Model", field: "model", width: 100},
      {headerName: "Price", field: "price", width: 100}
    ];

    // specify the data
    var rowData = [
      {row: 1, make: "Toyota", model: "Celica", price: 35000},
      {row: 2, make: "Ford", model: "Mondeo", price: 32000},
      {row: 3, make: "Porsche", model: "Boxter", price: 72000},
      {row: 4, make: "Toyota", model: "Celica", price: 35000},
      {row: 5, make: "Ford", model: "Mondeo", price: 32000},
      {row: 6, make: "Porsche", model: "Boxter", price: 72000},
      {row: 7, make: "Toyota", model: "Celica", price: 35000},
      {row: 8, make: "Ford", model: "Mondeo", price: 32000},
      {row: 9, make: "Porsche", model: "Boxter", price: 72000}
    ];

    // let the grid know which columns and what data to use
    var gridOptions = {
      columnDefs: columnDefs,
      rowData: rowData,

    };

  // 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>

The problems in this sample are:

  1. The row number is defined in the data, which is not supported in real case. Maintaining a row is difficult and slow since inserting from the beginning will need to update many rows.
  2. Since the row number is defined in the data, after sorting you won't see the row number is randomized. I still want to see the row number start from 1 from the beginning.

Basically it's easier to be part of the grid feature, and many other grids (not limited to JS grids) support this. I'm wondering if it's easy to do it in with ag-grid.

Kedron answered 22/5, 2018 at 22:47 Comment(8)
What have you tried? Are you expecting tens, hundreds, or thousands of rows in your grid?Pullen
@AndyKing Yes, I'm expecting up to 100K rows (of data) in my grid. So row virtualization is required also.Kedron
If the user scrolls through the grid are you expecting the number for any specific row to change as the top row disappears from the grid? For example, if the row that contains "a" is initially at the top of the grid, and the row that contains "b" is in the second row, you'd have "1" on the "a" row and "2" on the "b" row, but when the grid is scrolled the number for the "b" row will suddenly change from "2" to "1" when the "a" row disappears?Pullen
@AndyKing No, B is the 2nd row so it's always 2 before B - but if (after sorting) B becomes the first row then it's 1 before B. It's a very simple requirement. I've updated the questions with a sample and more descriptions. Hope it helps to clarify my requirement. Thanks.Kedron
I would ask the ag-grid team to add an enhancement to the grid that facilitates this. It seems like a good request, and it doesn't seem too difficult.Pullen
Hi. Has it been done? I found this but not the best, ie. would expect row number update to always be in the same order even if sorting a column in a different order: ag-grid.com/javascript-grid-infinite-scrollingIncognizant
@JeffreyZhao, have you found any solution for this?Beery
@Beery Yes, we simply added a column with a valueGetter to return rowIndex and programically refresh this column when data changed (in batch) or sorted.Kedron
W
44

Ag-grid now has a "valueGetter" for cells that takes an expression, so you can just use

columnDefs: [
  {
    headerName: "Row",
    valueGetter: "node.rowIndex + 1"
  },
  (other columns)
]

In order to have it refresh after sorting, you need to call refreshCells:

onSortChanged(e: AgGridEvent) {
  e.api.refreshCells();
}

If you are filtering, you would do the same thing on the 'filterChanged' event.

Welcy answered 28/2, 2020 at 16:19 Comment(3)
This is a simple, elegant solution without much fuss.Uwton
but is this best if we have 100k rows in the grid? this will try to refresh 100k cells r8? will that impact performance?Beery
@Beery - I'm pretty sure that Ag Grid virtualization means that only displayed rows get refreshed -- plus it uses change detection to only refresh cells that change. And you can give a column as a parameter to only look at the one column. ag-grid.com/javascript-data-grid/view-refresh. Try it, but I think you will find that there is no performance impact.Welcy
A
2

One way that we can use is: create a custom component that implements "ICellRendererAngularComp" interface refer to https://www.ag-grid.com/javascript-grid-cell-rendering-components/#example-rendering-using-angular-components and implements agInit method like below:

import { ICellRendererAngularComp } from 'ag-grid-angular';
import { Component } from '@angular/core';

@Component({
  selector: 'app-ag-grid-row-number',
  templateUrl: './ag-grid-row-number.component.html',
  styleUrls: ['./ag-grid-row-number.component.scss']
})
export class AgGridRowNumberComponent implements ICellRendererAngularComp {

  rowNumber: number;
  refresh(params: any): boolean {
    return true;
  }
  agInit(params: import('ag-grid-community').ICellRendererParams): void {
    this.rowNumber = params.rowIndex + 1;
  }
  afterGuiAttached?(params?: import('ag-grid-community').IAfterGuiAttachedParams): void {

  }

}

In your view:

{{ rowNumber }}

finally in your list component:

public columnDefs = [
    {headerName: 'row number', cellRendererFramework: AgGridRowNumberComponent}, 
... ]
Agatha answered 29/8, 2019 at 13:0 Comment(0)
R
1

You can create many custom Column types in some kind of utility file and import them when needed:

import { ColDef } from 'ag-grid-community';

export const rowNumber: ColDef = {
    width: 50,
    filter: false,
    sortable: false,
    resizable: false,
    suppressMenu: true,
    suppressMovable: true,
    enableRowGroup: false,
    suppressAutoSize: true,
    suppressSizeToFit: true,
    headerName: '#',
    colId: 'rownumber',
    headerClass: 'cell-center',
    cellStyle: { textAlign: 'center' },
    valueGetter: 'node.rowIndex + 1',
    valueFormatter: 'node?.rowPinned ? "" : x'
}

// More types can be defined
import { rowNumber } from './grid-utility';

gridOptions: GridOptions = {
    columnDefs: [
        { type: 'rowNumber' }
    // Other columns
    ]

    columnTypes: {
        rowNumber
    }

    // Other options
}
Ricketts answered 20/6, 2024 at 14:41 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.