I'm trying to clear an input when a user presses comma (,). So what I did was, on (keypress)
I would check the keyCode
and if it's a comma I would clear the input by setting the input value to input.value = ''
.
HTML:
<input type="text" #elem (keypress)="clearInput($event)">
Code:
@ViewChild( 'elem' ) public element;
clearInput( e: KeyboardEvent ) {
if ( e.keyCode === 44 ) {
this.element.nativeElement.value = '';
} else {
console.log('Not a comma');
}
}
I'm trying to clear an input when a user presses comma (,). So what I did was, on (keypress)
I would check the keyCode
and if it's a comma I would clear the input by setting the input value to input.value = ''
.
HTML:
<input type="text" #elem (keypress)="clearInput($event)">
Code:
@ViewChild( 'elem' ) public element;
clearInput( e: KeyboardEvent ) {
if ( e.keyCode === 44 ) {
this.element.nativeElement.value = '';
} else {
console.log('Not a comma');
}
}
Share
Improve this question
edited Oct 17, 2019 at 10:06
Brian Tompsett - 汤莱恩
5,88372 gold badges61 silver badges133 bronze badges
asked Aug 8, 2018 at 10:46
user3607282user3607282
2,5556 gold badges37 silver badges65 bronze badges
0
3 Answers
Reset to default 11Use Event.preventDefault().
Add preventDefault()
in your clearInput
code as shown below:
clearInput (e: KeyboardEvent) {
if (e.keyCode === 44) {
e.preventDefault(); // <-- Here
this.element.nativeElement.value = '';
} else {
console.log('Not a comma');
}
}
Simply return false
if a comma is pressed:
class HomeComponent {
@ViewChild('elem') public element;
clearInput(e: KeyboardEvent) {
if (e.keyCode === 44) {
this.element.nativeElement.value = '';
return false;
} else {
console.log('Not a comma');
}
}
}
JSFiddle: https://jsfiddle.net/lucakiebel/zrehcwfy/1/
You need to do 2 minor changes:
- Use
keyup
event to get the latest key typed and include in the value ofinput
- Use
e.key === ','
in theif
condition
Here is the working JSFIDDLE