handling multiple dropdown button opening at same time in Angular

1.7k Views Asked by At

I am working in Angular ,

  • Where I have created a tree based structure
  • on going down to tree structure there is a dropdown button name "Dropdown"
  • Problem is on clicking to "Dropdown" button multiple dropdown is opening at same time
  • Kindly check I am putting stackblitz link below for the code

https://stackblitz.com/edit/angular-tree-un?file=src%2Fapp%2Fapp.component.html

3

There are 3 best solutions below

0
On BEST ANSWER

The button needs to toggle the corrosponding node. Everytime the dropdown button is clicked the value which determines if the dropdown should change in the node. Add isSelected as a property to the nodes and check if a node should show based on this property. Im not sure why you handle that vaccant node like that but the normal nodes should just work like this. Using Akhil's code since you've already tested it adjust it to this:

{ 
name: "Raghavendran M",
me_code: "6000001",
tl_code: "N.A.",
rs_id: "09565792-c288-4885-a4ed-3dd055f250f5",
role: "ME",
isSelected:false 
}


myFunction(value,node){
    node.isSelected = !node.isSelected;
    }
  }
<div class="dropdown">
<button (click)="myFunction(1,node)" class="dropbtn">Dropdown</button>
<div id="myDropdown" class='dropdown-content' *ngIf='node.isSelected' >
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
1
On

Instead of writing if(1) and if(2), keep the condition like below:

     if(value===1){ 
        this.availableBtn = !this.availableBtn;
     }

     if(value===2){
        this.vaccanttoggle = !this.vaccanttoggle;
     }
1
On

Try this.. added extra property isSelected for TREEDATA children

{ 
name: "Raghavendran M",
me_code: "6000001",
tl_code: "N.A.",
rs_id: "09565792-c288-4885-a4ed-3dd055f250f5",
role: "ME",
isSelected:false 
}


myFunction(value,node){
    if(value==1){
       this.availableBtn = !this.availableBtn;
       if(!this.availableBtn){
          node.isSelected=false;
       }else{
        node.isSelected=true;
       }
    }

    if(value==2){
       this.vaccanttoggle = !this.vaccanttoggle;
    }
  }

in HTML ->

<div class="dropdown">
<button (click)="myFunction(1,node)" class="dropbtn">Dropdown</button>
<div id="myDropdown" class='dropdown-content' *ngIf='availableBtn && node.isSelected' >
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>

stackblitz