我最近问过this question,答案很好。
但是我还有另一个问题:如何在有多个下拉菜单的ng-bootstrap下拉菜单中检测切换状态?
当I try doing it仅返回firstdropdown的状态时。我不能使用唯一的ID,因为它们不包含'isopen()'方法。
如何在有多个下拉菜单的ng-bootstrap下拉菜单中检测切换状态?
答案 0 :(得分:3)
我会做这样的事情:
我使用ViewChildren
@ViewChildren(NgbDropdown)
dropdowns: QueryList<NgbDropdown>;
dropdown: NgbDropdown;
然后,我将以这种方式更改checkDropDown
方法:
checkDropDown(dropdown: any) {
// Check which dropdown was clicked
this.dropdown = this.dropdowns.find(x => (x as any)._elementRef.nativeElement == dropdown)
// Check if the clicked dropdown is open
console.log(this.dropdown.isOpen())
}
您还应该通过使用模板ref来更改html文件:
<div #drop1 ngbDropdown>
<button class="btn btn-outline-primary" ngbDropdownToggle (click)="checkDropDown(drop1)">Toggle-1</button>
...
<div #drop2 ngbDropdown>
<button class="btn btn-outline-primary" ngbDropdownToggle (click)="checkDropDown(drop2)">Toggle-2</button>
我也在这里工作StackBlitz。
P.S。您的按钮具有相同的ID,请将其删除:dropdownConfig
答案 1 :(得分:1)
为什么不使用(openChange)?参见stackblitz
<div #drop1 ngbDropdown (openChange)="checkDropDown($event,1)">
<button class="btn btn-outline-primary" ngbDropdownToggle >Toggle-1</button>
<div ngbDropdownMenu aria-labelledby="dropdownConfig">
<button ngbDropdownItem>Action - 1</button>
<button ngbDropdownItem>Another Action</button>
<button ngbDropdownItem>Something else is here</button>
</div>
</div>
注意:如果我们可以参考该下拉菜单,我们会写
<div #drop1="ngbDropdown"
ngbDropdown (openChange)="checkDropDown($event,drop1)">
....
</div>
checkDropDown(open:boolean,dropdown: NgbDropdown) {
console.log(open,dropdown.placement)
}
更新,ngbDropdown的正式文档为here。难以理解API,因此,尝试说明一下
输入是可以在.html中添加为
的属性<div ngbDropdown [propertie]="variable"..>
//or
<div ngbDropdown propertie="valor" ...>
//if is a string, don't forget use simple quotes e.g.
<div ngbDropdown autoClose="'outside'" ...>
输出子“事件”,如果返回一个值,我们将使用$ event获得响应,例如
<div ngbDropdown (openChange)="myFunction($event)" ...>
//If we can send more arguments, simply
<div ngbDropdown (openChange)="myFunction($event,"some more")" ...>
方法是可以在.ts中使用的方法,因为我们有一个ViewChild或ViewChildren
<div #myngbDropdown ngbDropdown [propertie]="variable"..>
@ViewChild('myngbDropDown') mydrop:nhbDropDown;
ngOnAtferView()
{
console.log(this.mydrop.isOpen())
}