dirtyw0lf
dirtyw0lf

Reputation: 1958

Passing data from Directive to Component in Angular

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?

Upvotes: 1

Views: 4107

Answers (1)

Lazy Coder
Lazy Coder

Reputation: 1217

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.

Upvotes: 4

Related Questions