user3607282
user3607282

Reputation: 2555

How to clear an input value on some button press?

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

Upvotes: 18

Views: 3033

Answers (3)

UtkarshPramodGupta
UtkarshPramodGupta

Reputation: 8152

Use 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');
   }
}

Upvotes: 11

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

You need to do 2 minor changes:

  1. Use keyup event to get the latest key typed and include in the value of input
  2. Use e.key === ',' in the if condition

Here is the working JSFIDDLE

Upvotes: 0

Luca Kiebel
Luca Kiebel

Reputation: 10096

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/

Upvotes: 7

Related Questions