I'm looking for a way to bind a function to my whole page (when a user presses a key, i want it to trigger a function in my conponent.ts)
It was easy in Angular 1 with a ng-keypress
but it does not work with (keypress)="handleInput($event)"
.
I tried it with a div wrapper on the whole page but it doesn't seem to work. it only works when the focus is on it.
<div (keypress)="handleInput($event)" tabindex="1">
Thank you!
yurzui's answer didn't work for me, it might be a different RC version, or it might be a mistake on my part. Either way, here's how I did it with my component in Angular2 RC4 (which is now quite outdated).
I would use @HostListener decorator within your component:
There are also other options like:
host property within
@Component
decoratorAngular recommend using
@HostListener
decorator over host property https://angular.io/guide/styleguide#style-06-03renderer.listen
Observable.fromEvent
If you want to perform any event on any specific keyboard button press, in that case, you can use @HostListener. For this, you have to import HostListener in your component ts file.
import { HostListener } from '@angular/core';
then use below function anywhere in your component ts file.