1

Please help with this as I am very new to angular. So in my html, I have this event binding where it would open up a document when a user clicks using the mouse.

<div
    fxFlex="1 1 auto"
    fxLayout="column"
    class="content"
    (click)="openDialog($event)">

Besides using (click), how can I also trigger the openDialog event to open using Enter key from the keyboard? Right now it doesn't do anything when I try to use the enter key.

J.TrLu
  • 65
  • 1
  • 12

2 Answers2

1

Try (keyup.enter) or (keydown.enter)

<div
    fxFlex="1 1 auto"
    fxLayout="column"
    class="content"
    (click)="openDialog($event)"
    (keyup.enter)="openDialog($event)"
>

Keep in mind that $event is now the keyboard event and not the click event.

AliF50
  • 16,947
  • 1
  • 21
  • 37
  • It doesn't work. The mouse (click) works but using enter keyboard doesn't do anything. Can I have both click and keyboard events? – J.TrLu Mar 24 '21 at 20:11
  • I think you can but try removing the click event and only having the enter event. – AliF50 Mar 24 '21 at 20:13
  • I tried to remove (click) and only use (keyup.enter) but that doesn't do anything either. Am I missing something here? – J.TrLu Mar 24 '21 at 20:23
  • https://stackoverflow.com/questions/50129245/angular-5-button-submit-on-enter-key-press It seems to be working there, I am not sure why it's not working for you. Maybe you have to give it to a button or an input element but I see somebody doing it for a div element. – AliF50 Mar 24 '21 at 20:45
  • 1
    I think I found out the issue. I have the focus on the wrong
    hence it didn't trigger the event. By moving the focus to the right div where event is trigger, I was able to use (keyup.enter). Thanks for your help.
    – J.TrLu Mar 24 '21 at 21:27
0

You can use a HostListener decorator on the method in your *.ts file without changing the template.

See this stackblitz for example.

Just be sure in your case, to check that the dialog you want to open was not opened already.

export class App {
  enterCounter = 0;
  tCounter = 0;

  @HostListener('document:keydown.enter')
  onDocumentKeydownEnter() {
    this.enterCounter++;
  }

  @HostListener('document:keyup.t')
  onDocumentKeyupT() {
    this.tCounter++;
  }
}
Max
  • 59
  • 2
  • 9