Jaffakex
Jaffakex

Reputation: 538

Use Enter key to navigate to cell below in AG-Grid

We need to edit the cell navigation in AG-Grid but I am not finding a way to do what we need. This is not a huge change but a crucial change for our users. The navigation rules we need is similar to Google Spreadsheet cell navigation.

The following rules should apply:

We are using AngularJS.

Upvotes: 5

Views: 14165

Answers (3)

Iosif Petre
Iosif Petre

Reputation: 188

On ag-grid there are 2 inputs you can set to achieve excel style behavior for the Enter key: enterNavigatesVertically and enterNavigatesVerticallyAfterEdit.

See documentation: https://www.ag-grid.com/angular-data-grid/cell-editing-start-stop/#enter-key-navigation

Upvotes: 0

Jaffakex
Jaffakex

Reputation: 538

EDIT:

This feature has been added to AG-Grid! Documentation here.

Original (Outdated) answer:

We ended up asking on AG-Grid forum. There was no easy or clean way to do this. Basically you add an event to the grid that listens to 'Enter' being pressed and then manually move the focus down one row.

You have to know if the user is currently editing when the 'Enter' event is fired and also watch out if the user is on the last line.

gridDiv.addEventListener('keydown', function(evt) {
  if(editing && evt.key === 'Enter') {
      var currentCell = gridOptions.api.getFocusedCell();
      var finalRowIndex = gridOptions.api.paginationGetRowCount()-1;

      // If we are editing the last row in the grid, don't move to next line
      if (currentCell.rowIndex === finalRowIndex) {
          return;
      }
      gridOptions.api.stopEditing();
      gridOptions.api.clearFocusedCell();

      gridOptions.api.startEditingCell({
        rowIndex: currentCell.rowIndex + 1,
        colKey: currentCell.column.colId
      });
  }
});

The editing flag is managed manually in grid options.

var editing = false;

var gridOptions = {
    columnDefs: columnDefs,
    rowData: students,
    onCellEditingStarted: function (evt) {
        editing = true;
    },
    onCellEditingStopped: function (evt) {
        editing = false;
    }
};

Here is a working plunker example:
https://plnkr.co/edit/quhyS05SSVzmuDlCErZD?p=preview

Upvotes: 12

BMW
BMW

Reputation: 499

You can also use the 'keydown' event to globally track the last key pressed, a variant of your answer.

let eventKey;
let validKeys = ['Enter'];

gridDiv.addEventListener('keydown', function(event) {
    eventKey = event.key;
});

onCellEditingStopped: function (event) {
    if(validKeys.includes(eventKey)){
        var currentCell = gridOptions.api.getFocusedCell();
        var finalRowIndex = gridOptions.api.paginationGetRowCount()-1;

        if (currentCell.rowIndex === finalRowIndex) {
            return;
        }

        gridOptions.api.startEditingCell({
            rowIndex: currentCell.rowIndex + 1,
            colKey: currentCell.column.colId
        });
    }
}

Upvotes: 0

Related Questions