Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent user from firing space in a textbox

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?

like image 441
anonym Avatar asked Dec 29 '16 07:12

anonym


2 Answers

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

like image 106
Milad Avatar answered Oct 31 '22 04:10

Milad


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();
}
like image 42
Robba Avatar answered Oct 31 '22 03:10

Robba