1

I am trying to detect the enter key event when on a form submit, The enter key event works only if there any value present in any of the form components.

But the enter key event is not working in the case of the empty form (ie no value present in any of the form elements)

<form (keydown)="keyDownFunction($event)">
  <input type="text" />
</form>

Ts file

keyDownFunction(event) {
        if (event.keyCode === 13) {
          alert("you just pressed the enter key");
          // rest of your code
        }
      }

Here is the stackbliz URL https://stackblitz.com/edit/angular-7v744e

shamon shamsudeen
  • 5,466
  • 17
  • 64
  • 129
  • For me the alert appears even if the field is empty (which I kind of expected, given that it absolutely shouldn't matter whether the fields are empty or not). Also, it might be more useful to detect a form submission event instead. –  May 03 '21 at 05:35
  • Could you please bit more about form submission event – shamon shamsudeen May 03 '21 at 05:38
  • Use the `(ngSubmit)` handler instead. –  May 03 '21 at 05:45

1 Answers1

1

It's a matter of the focus. If you hit enter while your cursor is not focused on the form, the event won't register, similar to if you have a click event and you click outside of the scope.

If you're in focus, the enter will be caught, even if the form is empty.

To get around this, you should have your form in focus as soon as it loads. This answer here shows one way to achieve this, and this answer shows another.

PMO1948
  • 2,210
  • 11
  • 34