1

I have following html code, I need to identify whether the event is mouse click event or keyboard enter key event.

Html code

    <button mat-raised-button class="btn-enter-troubleshooting-attempts" 
(click)="triggerLog($event)"> Click/Enter </button>

Type script

triggerLog(e): void {
    console.log('Log Attempt', e);
   //do some function based on the event
  }

3 Answers 3

1

You can add (keydown)="triggerLog($event)" and then check if the Enter key is pressed in app.component.ts:

triggerLog(e): void { 
  console.log('Log Attempt', e);

  if(e.code === 13) {
    // Enter pressed.
  }
}

If you want to listen to keypress or keydown with no selection:

ngOnInit(): void {
  window.addEventListener('keydown', this.triggerLog, true);
} 

You can check keyboard codes at https://keycode.info/.

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

5 Comments

if we write (keypress) then mouse click is not working, then how to handle that situation
add window event to ngOnInit
``` ngOnInit(): void { window.addEventListener('keydown', this.triggerLog, true) } ```
Note both keypress and e.keyCode are depreacted, so you should probably be using e.key or e.code instead. Also, this line is wrong: e.code === 13. You have 4 alternatives there: e.key === 'Enter', e.code === 'Ender', e.which === 13 (deprecated) or e.keyCode === 13 (deprecated).
Also, take a look at this other tool keyjs.dev, that has a bit more information about the different keyboard events and their properties. 🙂
0

Use (keyup.enter) to bind to enter key. Use (click) to listen to mouse clicks.

Check this link

2 Comments

(click) can able to handle mouse click and enter key event, but (keyup.enter) only able to perform when press enter key. So you r trying to say that (click)="triggerLog($event)" (keyup.enter) = "triggerLog($event)" i need to use both together
Technically, after thinking about it, user should not be able to press enter key on a button element. if user is able to navigate to a button by pressing tab key, then you could always set tabIndex="-1" on a button to skip selection on this button.
0

you only need ask about event.clientX, if has any value is a click, else is an ENTER

<form [formGroup]="form">
    <input formControlName="name">
    <button type="submit" (click)="triggerLog($event)">click</button>
</form>

  form=new FormGroup({
    name:new FormControl('')
  })
  triggerLog(event)
  {
    console.log(event.clientX)
  }

See simple stackblitz

Comments

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.