Danaley
Danaley

Reputation: 803

Conflicts when having multiple Angular @HostListener in different components

It's my first time doing this.

I have @Hostlistener in app.component to listen for 'ESC'. (acts like a global listener)

@HostListener('document:keydown', ['$event'])
    public onKeydownHandler(event: KeyboardEvent): void {
    ....... // listens for 'ESC'
}

and I have another @Hostlistener in input.component (listen for 'ENTER' in input fields)

 @HostListener('keydown', ['$event'])
    public onKeydownHandler(event: KeyboardEvent): void {
    ....... // listens for 'ENTER'
    }

What happens now is when I am not in the input fields, 'ESC' will be detected. When I am in the input fields, 'ESC' will not be detected.

Expected behavior: 'ESC' should be detected even inside the input fields.

It seems like the global listener doesn't work like I expected. Is this the correct behavior?

Upvotes: 2

Views: 6405

Answers (1)

Prithivi Raj
Prithivi Raj

Reputation: 2736

Use directives to listen only to the input field. Working demo

<input placeholder="Can't copy/paste" type="text" litsenEnter/>

Directive file

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

@Directive({
  selector: '[litsenEnter]'
})
export class LitsenEnter{
  constructor() { }

   @HostListener('keydown', ['$event'])
    public onKeydownHandler(e: KeyboardEvent): void {
    if(e.keyCode===13){
      alert("enter")
    }
    }
}

Global Escape event in app.component.ts

import { Component } from '@angular/core';
import {  HostListener } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @HostListener('document:keydown', ['$event']) triggerEsc(e: KeyboardEvent) {
    if(e.keyCode===27){
      console.log("global esc");
      alert("esc");
    }
  }

  name = 'Angular 5';
}

Upvotes: 2

Related Questions