To disable the selection of options in a dropdown via keyboard input, you can use the keydown event and prevent the default behavior when a printable character (letter) is pressed.
Create directive.
import { Directive, ElementRef, HostListener } from '@angular/core';
/**
* Directive to disable keyboard support for printable characters in a dropdown.
* Prevents selection of options when typing letters.
*/
@Directive({
selector: '[appDisableDropdownKeyboard]',
})
export class DisableDropdownKeyboardDirective {
constructor(private elementRef: ElementRef) {}
/**
* Event listener for the 'keydown' event on the host element.
* Prevents the default behavior for printable characters (letters) and stops event propagation. Not arrow donw, up etc..
* @param event The keyboard event.
*/
@HostListener('keydown', ['$event'])
onKeydown(event: KeyboardEvent) {
event.stopPropagation();
const printableCharacters = /[a-zA-Z]/;
if (printableCharacters.test(event.key)) {
event.preventDefault();
}
}
}
Declare directive in app.module.ts or any of your module
declarations: [
DisableDropdownKeyboardDirective,
],
And in HTML add directive.
<p-dropdown
appDisableDropdownKeyboard
[options]="cities"
[(ngModel)]="selectedCity2"
editable="true"
optionLabel="name"
></p-dropdown>
And edited Your Stackblitz