Reputation: 1713
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
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:
(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()">
Upvotes: 2