I am trying to build an angular2 application with multiple components. It is built using custom and many third party UI components. One of the tree component I use, registers a global keyDown listener on the document using @Hostlistener. One of my component has a table with multiple selection. So a simple select action using 'ctrl' key fires the handler of the tree component.
My sample usecase
- I have a MyTreeComponent which has a tree. The tree needs to handle the 'delete' key and delete the node
- There are 4-5 instances of MyTreeComponent (imagine an accordion with multiple trees inside)
I register a listener on keydown in my component which has the tree like below :
import {HostListener, KeyboardEvent} from '@angular/core';
@Component({...})
export class MyTreeComponent {
@HostListener('document:keydown', ['$event'])
onKeyDown(event:KeyboardEvent) {
// check if the event is a delete and perform delete action
}
}
- I have another component with a table which has a row multi select functionality.
So if I multiselect using the ctrl' key in my tablecomponent the 'onKeyUp()' of all the 4-5 MyTreeComponent instancea gets fired and too many times.
This is slowing down the performance quite significantly. Any thoughts how this could be improved ?
Also a couple of questions
- Is there a way to register a component specific Hostlistener ?
- Is there a way to know which component is currently active (or in focus) at any point in time ? So that i could add and remove @Hostlistner dynamically (if it is possible)
Thanks in advance for help