3

I am trying to hit enter key to press a button on my login form. However it does not. The code looks like:

<div>
  <button type="button" mat-raised-button (click)="doLogin()" (keyup.enter)="doLogin()">
    Sign In
  </button>
</div>

I have no idea why it is not firing. No error in console and angular documentation does not indicate any special requirement for it to work.

The.Bear
  • 5,621
  • 2
  • 27
  • 33
Vik
  • 8,721
  • 27
  • 83
  • 168

3 Answers3

3

If the controls are in a form, the ngSubmit event will be triggered when Enter is pressed. To also trigger the event by clicking the button, you should remove the attribute type="button". The default type is type="submit" when the button is in a form.

<form (ngSubmit)="onNgSubmit()">
  <div>
    <input type="text" name="username" placeholder="User name" />
    <button mat-raised-button>Sign In</button>
  </div>    
</form>
export class UserFormComponent {
  onNgSubmit() {
    // Proceed with login...
  }
}

You can test the code in this stackblitz.

ConnorsFan
  • 70,558
  • 13
  • 122
  • 146
2

You are trying keyup on a button, button does not have that event, instead you should try on input of form

<form >
  <input type="text" (keyup.enter)="doLogin()" />
</form

EDIT

if you want to get this fired when submitting use

 <form (ngSubmit)="doLogin()">
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
1

Try this. This works just fine for me. Hope it helps!

<form>
  <input type="text" (keyup.enter) = "doLogin($event)">
</form>

In your component:

doLogin(e){
 console.log(e);
}
HenryDev
  • 4,685
  • 5
  • 27
  • 64