Prevent user from firing space in a textbox

2020-08-17 12:13发布

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?

4条回答
看我几分像从前
2楼-- · 2020-08-17 12:49

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

查看更多
Ridiculous、
3楼-- · 2020-08-17 13:02

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>
查看更多
Fickle 薄情
4楼-- · 2020-08-17 13:08

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();
}
查看更多
祖国的老花朵
5楼-- · 2020-08-17 13:14

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

查看更多
登录 后发表回答