phunder
phunder

Reputation: 1713

Basic key pressed detection in Angular not working as expected

I am a React developer who is fairly new to Angular working on a project that was built by a more experienced colleague of mine who is not available to ask for help at the moment. I am trying to do what I believe should be fairly simple. I have found many posts asking for the same help, but none of their solutions seems to work for me.

I simply want to fire a function when the user clicks the enter key on their keyboard. I have been trying the following:

<button type="button" fxFlex="140px" mat-raised-button color="warn" ng-keydown="$event.keyCode === 13 && searchItem()" (click)="onSendEmail(forgotFormElement)" [disabled]="forgotForm.invalid">Send</button>      

I found the following snippet in the code already part of the solution, and it fires the onSendEmail function perfectly:

(click)="onSendEmail(forgotFormElement)"

I have read that you can also write this as something like:

ng-click="onSendEmail(forgotFormElement)"

I am assuming the different approaches points to different versions of Angular, and this lead me to try the following:

 <button type="button" fxFlex="140px" mat-raised-button color="warn" (keydown)="$event.keyCode === 13 && searchItem()" (click)="onSendEmail(forgotFormElement)" [disabled]="forgotForm.invalid">Send</button>

None of these worked any better.

I have tried a few other approaches, even removing the key code check to see if it fires if I press any button, but after an hour of getting nowhere, I thought I would ask the Stack Overflow community for help. Does

Upvotes: 0

Views: 3183

Answers (1)

user3740359
user3740359

Reputation: 405

Based on the fact that you want to execute the action when the enter key is pressed not on the button itself, but in other inputs / textfields you could do one of the following:

  1. Bind the (keyup) event on the input fields directly. I would recommend this if the amount of input fields is pretty small - e.g. for a login form.
<input (keyup)="$event.keyCode === 13 && searchItem()">
  1. Listen for the keyup event globally. So a enter press anywhere on the page would trigger the action. You find details about that here How can I listen for keypress event on the whole page?

Upvotes: 2

Related Questions