0

I am using angular 8 and need to default click a button on a page when Enter key is pressed. The thing is the button is not inside any form. There are other buttons beside it. Clicking them works fine, but I need to press this one on Enter key press. I read some suggestions but none seems fitting in. I tried `(keyup.Enter)="search()" but it didn't work.

<button
            id="log-button"
            (click)="search()"
            color="primary"
            [disabled]="logForm.invalid"
            class="link-button"
            >Search</button
        >

P.S. - Though there is logForm here but it's only for validation purpose and there isn't any <form> tags in the html where this button is placed.

Any help us much appreciated.

R. Richards
  • 24,603
  • 10
  • 64
  • 64
a p
  • 1,121
  • 6
  • 26
  • 51

1 Answers1

2

You should listen to key-down event inside the ts file

 @HostListener('document:keypress', ['$event'])
  handleKeyboardEvent(event: KeyboardEvent) { 
  if(this.key === "Enter")
    your event
  }

excemple of lisener

Roman Epifanov
  • 108
  • 1
  • 6
  • I just figured that out mate after reading number of solutions and none worked. I figured it and your reply popped. Thanks a bunch though. This one works like a charm. Accepting it. – a p Jun 29 '20 at 14:33