Is it possible to use HostListener in a Service? Or how to use DOM events in an Angular...

Discussão em 'Angular' iniciado por trelltron, Abril 8, 2025.

  1. trelltron

    trelltron Guest

    I want to create a service which detects all keyboard input, translates the key strokes into actions based on a configurable mapping, and exposes observables which various elements can bind to to react to specific key presses.

    The following is a simplification of my code so far, it worked when HostListener was in a component, but now I've moved it into a service it never fires even though it is definitely initialised. Is it not possible to detect input like this in a service?

    import { Injectable, HostListener } from '@angular/core';

    import { Subject } from 'rxjs/Subject';

    @Injectable()
    export class InputService {

    @HostListener('window:keydown', ['$event'])
    keyboardInput(event: any) {
    console.log(event);
    }
    }

    Continue reading...

Compartilhe esta Página