Search code examples
angulardropdown

How to access each dropdown out of several dropdowns


How can I access each of my dropdowns using viewchildren?

The dropdowns are populated through an ngfor.

Using viewchildren, whenever I click to open one, the other doesn't close or at times it won't open. Please help.

   <div #dropdown class="dropdown is-right" [id]="comment._id">
          <div class="dropdown-trigger">
            <a class="actionBtn" aria-haspopup="true" aria-controls="dropdown-menu3" (click)="toggleDropdown(comment._id)">
                <img src="../../../../assets/more.png" alt="">
            </a>
          </div>
          <div>
              <div class="dropdown-menu" id="dropdown-menu3" role="menu">
                  <div class="dropdown-content">
                    <a href="#" class="dropdown-item">
                      Overview
                    </a>
                    <a href="#" class="dropdown-item">
                      Modifiers
                    </a>
                  </div>
                </div>
          </div>
        </div>


@ViewChildren('dropdown') dropDown: QueryList<any>

toggleDropdown(comment_id) {
this.dropdown = this.dropDown.find(x => x.nativeElement.attributes.id.nodeValue == comment_id)
if (this.dropdown.nativeElement.classList.contains('is-active') === false) {
  this.dropdown.nativeElement.classList.add('is-active')
} else {
  this.dropdown.nativeElement.classList.remove('is-active')
 }
}

Solution

  • I assume you are trying to add the is-active class to the clicked dropdown and remove the same from all other dropdown. If that is the case, there is a flaw in your toggleDropdown logic. You are identifying the clicked dropdown using find from the dropDown array and toggling is-active class. But, you are not removing is-active class from any other dropdown which is already open. You can loop through all dropdowns - then toggle is-active class for the clicked dropdown and remove is-active from other dropdowns.

    toggleDropdown(comment_id) {
        this.dropDown.forEach(dropdown => {
            if(dropdown.nativeElement.attributes.id.nodeValue == comment_id){
                dropdown.nativeElement.classList.toggle('is-active');
            } else{
                dropdown.nativeElement.classList.remove('is-active')
            }
        });    
    }