1

Here is the directive, which listens to key strokes on any component:

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

@Directive({ selector: '[keyCatcher]' })
export class keyCatcher {
    @HostListener('document:keydown', [ '$event' ])
    onKeydownHandler(event: KeyboardEvent) {
        alert(event.key);
    }
}

the KeyCatcher is used in the HTML portion of a custom component.

How can I pass the event.key to the component.ts using the KeyCatcher?

Is this usually done through a service?

1
  • 1
    How does the dependency structure look? Is the directive used in the component that needs to be notified? If so just use an event (@Output) Commented Aug 9, 2019 at 19:23

1 Answer 1

4

Try something like this https://stackblitz.com/edit/angular-8rqqrc

Using an @Output of EventEmitter in the directive allows you to bind a function to it from the parent to read the event stream.

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

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.