How can I prevent a user from starting space in an Angular2 text box?

I used to look at the issue using jQuery as follows:

$("#textInput").keydown(function (e) { return e.which !== 32; }); 

How do you approach it with the new Angular and Typescript?

+6
source share
3 answers

Or simply:

 <input type="text" (keydown.space)="$event.preventDefault();"> 


I managed to create a convenient directive that is consistent with what 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 spaces, up, left, down, right: D

+8
source

You should use event binding in your template as follows:

 <input type="text" (keydown)="keyDownHandler($event)"/> 

Then in your controller, define the keyDownHandler() function:

 keyDownHandler(event: Event) { if (event.which === 32) event.preventDefault(); } 
+4
source

i just decalre $ at the top of my class like this

  declare var $: any; 

than you can use $ in your code, as you explained

 $("#textInput").keydown(function (e) { return e.which !== 32; }); 

Otherwise, there are various methods in angular2, such as keyup and keydown , etc. you can use them also

0
source

Source: https://habr.com/ru/post/1013595/


All Articles