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.

3
  • Can you show the ts file? Commented Mar 24, 2021 at 20:01
  • Added the ts portion where it called the openDialog Commented Mar 24, 2021 at 20:24
  • Not the spec ts but the component.ts Commented Mar 24, 2021 at 20:34

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

It doesn't work. The mouse (click) works but using enter keyboard doesn't do anything. Can I have both click and keyboard events?
I think you can but try removing the click event and only having the enter event.
I tried to remove (click) and only use (keyup.enter) but that doesn't do anything either. Am I missing something here?
stackoverflow.com/questions/50129245/… 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.
I think I found out the issue. I have the focus on the wrong <div> 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.
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++;
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.