Prevent Grid Checkbox Selection with the Enter Key
Environment
| Product | Progress® Kendo UI® for Angular Grid |
Description
How can I prevent the Enter key from changing a row selection when a Grid checkbox has focus?
This KB also answers the following questions:
- How can I stop
Enterfrom selecting a Grid row through a checkbox? - How do I prevent keyboard selection for a custom Grid checkbox column?
- How can I keep
Enterfrom changing checkbox-only selection in the Angular Grid?
Solution
To prevent Enter from changing selection, replace the built-in checkbox column with a custom column. Apply the SelectionCheckboxDirective to the custom checkbox and intercept keydown during the capture phase.
-
Add a directive that stops immediate propagation of the
Enterkey event before the Grid handles it. The following snippet defines the directive:tsimport { Directive, ElementRef, OnDestroy } from '@angular/core'; @Directive({ selector: '[preventSelectionOnEnter]' }) export class PreventSelectionOnEnterDirective implements OnDestroy { private readonly onKeyDown = (event: KeyboardEvent): void => { if (event.key === 'Enter') { event.stopImmediatePropagation(); } }; constructor(private readonly element: ElementRef<HTMLElement>) { this.element.nativeElement.addEventListener('keydown', this.onKeyDown, true); } public ngOnDestroy(): void { this.element.nativeElement.removeEventListener('keydown', this.onKeyDown, true); } }If your application uses server-side rendering, import
isDocumentAvailablefrom@progress/kendo-angular-commonand wrap bothaddEventListenerandremoveEventListenercalls in anif (isDocumentAvailable())check. -
Apply the directive to a custom checkbox that uses
kendoGridSelectionCheckbox. The following snippet defines the custom column:html<kendo-grid-column [width]="40"> <ng-template kendoGridCellTemplate let-rowIndex="rowIndex"> <kendo-checkbox [kendoGridSelectionCheckbox]="rowIndex" preventSelectionOnEnter [inputAttributes]="{ 'aria-label': 'Select row' }" ></kendo-checkbox> </ng-template> </kendo-grid-column>Checkbox selection is supported only in row selection mode and is not compatible with cell selection mode.
The following example demonstrates how to prevent Enter from changing row selection. Focus a checkbox and press Enter to verify that the row selection does not change.