简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM