Search code examples
angulardomdocumentangular2-directivesangular-directive

Close dropdown when second is opened / document.click blocked by click Angular 5


I am trying to create a directive for a drop-down, as long as I am working with single one it works like a charm. I can spot click outside dropdown using following code:

@HostListener('document:click', ['$event'])
  onDocumentClick(event: any): void {
    console.log("document click");
    // close
}
@HostListener('click')
  onClick(): void {
    console.log('click on ');  
    // toggle  
  }

The problem occurs when there are 2 dropdowns created. I would like close first drop-down when second is opened, however when I click on the second dropdown, only "click" event is getting triggered and "document.click" is not getting executed. I would expect that both events should occur unless I explicitly use preventDefault on click but apparently this happens automatically.

What should be correct approach in Angular 5 to close first drop-down when second is opened?


Solution

  • Maybe you can try something like this:

     @HostListener('document:click', ['$event'])
      onClick(event) {
        if(this.eRef.nativeElement.contains(event.target)) {
          // toggle logic
        } else {
          // close logic
        }
    }
    

    So instead of having two events conflicting with each other you would have one event with two pieces of logic to handle exactly what you need depending if you clicked inside or outside the element itself. Makes sense?

    This was taken from here