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?
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
(keydown.space) ? @Milad please add some explanationIn 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>
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