Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create keyboard shortcuts with Angular?

I'm having trouble trying to find a way to create keyboard shortcuts with it. I mean, where and how can I code something like ctrl + t increases font size of the site?

like image 854
Thiago Souza Avatar asked Mar 12 '26 06:03

Thiago Souza


1 Answers

Of course this can be accomplished with vanilla javascript, but Angular has the @HostListener decorator to make listening for events simpler: https://angular.io/api/core/HostListener

You put the decorator over a component's function to add an event listener that executes the function on an event.

Don't use ctrl + t though, that's "new tab" for all browsers, and I don't believe you can override it.

To listen for ctrl + b on the entire window it would be like this:

  @HostListener('window:keydown.control.b', ['$event'])
  bigFont(event: KeyboardEvent) {
    event.preventDefault();
    document.body.style.fontSize = '32px';
  }

event.preventDefault() prevents any default browser actions caused by the event, if possible.

Stackblitz: https://stackblitz.com/edit/angular-ivy-2rhyep?file=src/app/app.component.ts

Note: the listeners are cleaned up if the enclosing component is destroyed.

like image 139
Chris Hamilton Avatar answered Mar 14 '26 20:03

Chris Hamilton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!