Selecting Grid Rows with Up and Down Arrow Keys
Environment
Product | Progress® Kendo UI® for Angular Grid |
Description
How can I select the rows in the Kendo UI for Angular Grid using the up and down arrow keys?
Solution
To implement row selection in the Grid component when using the keyboard up and down arrows:
-
Use the
kendoGridSelectBy
directive of the Grid and define a unique item key, which will represent the selected items stored in theselectedKeys
collection:html<kendo-grid ... kendoGridSelectBy="ProductID" [(selectedKeys)]="mySelection" ></kendo-grid>
-
Enable the keyboard navigation of the Grid by setting the
navigable
property to true, which will allow focusing the Grid cells with the arrow keys. Then, handle the regularkeydown
event of the DOM and get a reference of the Grid component:html<kendo-grid #grid [navigable]="true" (keydown)="onKeyDown($event, grid)" ... ></kendo-grid>
-
In the event handler, use the
activeRow
property of the Grid to check the row associated with the currently focused cell. Update theselectedKeys
collection with the corresponding field of thedataItem
obtained from the availableactiveRow
data:tspublic onKeyDown(e: KeyboardEvent, grid: GridComponent): void { setTimeout(() => { if (grid.activeRow && (e.key === 'ArrowDown' || e.key === 'ArrowUp') && grid.activeRow.dataItem) { const rowId = grid.activeRow.dataItem.id; this.mySelection = [rowId]; } else { this.mySelection = []; } }); }
The following example demonstrates the full implementation of the suggested approach.