Search code examples
angularangular-directive

Creating custom dropdown component in Angular


I am trying to create my own dropdown component. The problem is, my dropdown works, but I have a few components which use this dropdown. When I click on their toggle buttons, multiple instances of dropdown menu is opened. Why is that happenning?

Here's the plunker

I want to see only one instance of dropdown visible at a time. My logic responsible for closing/opening dropdown:

@HostListener('document:click', ['$event'])
clickout($event) {
  if (this.eRef.nativeElement.contains($event.target)) {
    console.log('clicked inside!');
  } else {
    console.log('clicked outside!');
    if (this.isOpen) {
      this.isOpen = false;
    }
  }
}

And toggling:

@HostListener('click', ['$event'])
click($event) {
  const { offsetX, clientX, offsetY, clientY } = $event;
  const distances = {
    left: clientX - offsetX,
    top: clientY - offsetY
  };

  $event.stopPropagation();
  this.dropdown.toggle(distances);
}

How can I prevent opening another instance of dropdown while one is already opened? I want to close that and open another in a new place.


Solution

  • The $event.stopPropagation(); in the directive stops the propagation of the event to be handled by the other dropdown components.

    You should let the event propagate and find another way to close the dropdown. May be in the directive code ?

    I updated your example to fix the reported issue.

    You could find a more elegant way of fixing it.