12

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?

1

4 Answers 4

30

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

Sign up to request clarification or add additional context in comments.

2 Comments

what does this mean (keydown.space) ? @Milad please add some explanation
What about ALT+32? You can still enter space by pressing ALT and typing 32...
6

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();
}

Comments

5

In component you should implement this method .

onKeydown(event) {
if (event.keyCode === 32 ) {
  return false;
}

}

After that,In HTML tag,

<input type="text" class="form-control col-md-10" placeholder="First Name" (keydown)="onKeydown($event)" [value]="firstName" #newFirstName>

2 Comments

What exactly your answer adds to the existing ones in the thread, for instance this one?
this answer I very interesting, because I really don't know how can "return false" work.
-1

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

 declare var $: any;

than you are able to use $ in your code as you explained

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

Otherwise there are various methods in angular2 like keyup and keydown and so on you can use those also

2 Comments

This is not a good solution. Mixing jQuery and angular is not good practice. There are so many easier ways to do this as the other answers have provided.
@ChrisKooken I understand man, but at the time of answer written there were not so many ways to achieve this as compared to today :) Moreover I provided answer as per the question asked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.