Buu97
Buu97

Reputation: 168

Angular Directive, cannot attach event listener to element

I try to bind a keyup event to an input element inside an attribute directive. I've tried normal ways like element.nativeElement.onkeyup or element.nativeElement.addEventListener('keyup', () => {}) but when I type, nothing happens.

Now, I try using HostListener writing code like this

@HostListener('keyup', ['$event']) onKeyup(e) {}

UPDATE

Turns out, @HostListener has to be top level to work. But still, nothing happens when I type on the input. Here's the full code for the directive.

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

@Directive({
  selector: '[appKeyUp]'
})
export class KeyUpDirective implements OnInit {
    constructor(private el: ElementRef) { }

    ngOnInit() {
        console.log('directive initiated');
    }
    @HostListener('keyup', [$event]) onKeyUp(e) {
        console.log(e);
    }
}

What is going wrong this time?

Upvotes: 1

Views: 2818

Answers (1)

Maihan Nijat
Maihan Nijat

Reputation: 9355

Make a directive for the keypress event:

@Directive({
  selector: "[app-key-press]"
})
export class KeyupDirective {
  @HostListener("keyup", ["$event"]) onKeyUp(event: KeyboardEvent) {
    console.log(event);
  }
}

And use it on the input:

<input type="text" app-key-press />

That's all you need. Don't bind the event using element.nativeElement.onkeyup. All you need is to use the directive selector on the input.

Upvotes: 3

Related Questions