简体   繁体   中英

Angular dropdown toggle and closeOutside

I'm working on a nav component that has a couple of click events and I need your help :)

In my html I have

<ul class="nav-right">
<li (click)="toggleDropdown('item1')" (clickOutside)="clickEvent($event)">
  <span class="selector">
    my Selector
  </span>

  <ul *ngIf="isActive('item1')">
    <li *ngFor="let value of values">
          {{city.name}}
    </li>
  </ul>
</li>

<li (click)="toggleDropdown('other')" (clickOutside)="clickEvent($event)">
  <span class="selector">
    Other
  </span>
  <ul *ngIf="isActive('other')">
    <li *ngFor="let otherValue of otherValues">
        {{otherValue.name}}
    </li>
  </ul>
</li>

Then In my component I have a couple of events to toggle among components

toggleDropdown(menu: any) {
   this.activeMenu = this.activeMenu === menu ? 0 : menu;
}

isActive(menu: string): boolean {
  return this.activeMenu === menu;
}

And finally I use a directive to detect clicks outside nav

@Directive({ selector: '[clickOutside]' })
export class ClickOutsideDirective {
@Output() clickOutside = new EventEmitter<MouseEvent>();

constructor(private elementRef: ElementRef) { }

@HostListener('document:click', ['$event'])
onDocumentClick(event: MouseEvent): void {
const targetElement = event.target as HTMLElement;

if (targetElement && !this.elementRef.nativeElement.contains(targetElement)) {
  this.clickOutside.emit(event);
    }
  }
}

My problem is that I don't know how to check if the item clicked needs to be opened because I clicked in the item itself. I think those events collapse, but I don't know how to solve it, I'll be grateful if you give me a hint.

Thanks in advance!

So I found a pretty simple solution I'm posting here for future self and in case someone find it useful. It was only a matter of changing the position of certain elements

(clickOutside)="clickEvent($event)"

to

<ul class="nav-right">

So in the end my html markup is:

<ul class="nav-right" (clickOutside)="clickEvent($event)">
  <li (click)="toggleDropdown('item1')">
    <span class="selector">
     my Selector
    </span>

  <ul *ngIf="isActive('item1')">
     <li *ngFor="let value of values">
      {{city.name}}
    </li>
  </ul>
</li>

 <li (click)="toggleDropdown('other')">
   <span class="selector">
     Other
   </span>
   <ul *ngIf="isActive('other')">
     <li *ngFor="let otherValue of otherValues">
       {{otherValue.name}}
     </li>
   </ul>
 </li>
</ul>

Because what I wanted to achieve is to close all dropdowns when anyone clicks outside nav bar

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM