angular 2 material keyup.enter does not fire at all
Asked Answered
S

3

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.

Salot answered 4/2, 2018 at 21:21 Comment(0)
T
4

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.

Twotime answered 4/2, 2018 at 22:56 Comment(2)
the another issue was i did set name="username" but using [(ngModel)]Salot
Wha if the button is a dialog button that is not inside a form ?Disturbing
C
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()">
Confocal answered 4/2, 2018 at 21:23 Comment(2)
what do you mean? button is not an input elementConfocal
your above code doesnt work either i wrapped my login form around <form (keyup.enter)="doLogin()">Salot
R
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);
}
Righthanded answered 4/2, 2018 at 21:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.