Previously, I dealt with the problem using jQuery as follows:
$("#textInput").keydown(function (e) {
return e.which !== 32;
});
How would you approach it with the new Angular and Typescript?
Or simply ;
<input type="text" (keydown.space)="$event.preventDefault();">
I managed to create a handy directive which accepts what ever key number you give it and prevents them
@Directive( {
selector : '[prevent-keys]',
host : {
'(keydown)' : 'onKeyUp($event)'
}
} )
export class PreventKeyseDirective {
@Input( 'prevent-keys' ) preventKeys;
onKeyUp ( $event ) {
if ( this.preventKeys && this.preventKeys.includes( $event. keyCode ) ) {
$event.preventDefault();
}
}
}
And then use it like
<input [prevent-keys]="[32, 37 , 38 , 39 , 40 ]" type="text">
This will prevent space , up , left , down , right keys :D
You should use event binding in your template like this:
<input type="text" (keydown)="keyDownHandler($event)"/>
Then in your controller define the keyDownHandler()
function:
keyDownHandler(event: Event) {
if (event.which === 32)
event.preventDefault();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With