Reputation: 7332
I'm using NgbDropdown
in my angular application. I have two components CompParent and CompChild. Where compChild holds the HTML for dropdown and it is included into CompParent. I'm trying close all the opened dropdowns in page when a scroll event happens on scrollable-div
.
comp-child.component.html:
<div ngbDropdown container="body">
<button class="btn btn-outline-primary btn-sm" ngbDropdownToggle>Actions</button>
<div ngbDropdownMenu>
<button ngbDropdownItem>Edit</button>
<button ngbDropdownItem>Duplicate</button>
<button ngbDropdownItem>Move</button>
<div class="dropdown-divider"></div>
<button ngbDropdownItem>Delete</button>
</div>
</div>
And CompChild is included into CompParent like this:
comp-parent.component.html
<div class="scrollable-div" (scroll)="closeAllDropdowns($event)">
<div class="dropdown-container" *ngFor="let item of items">
<app-comp-child></app-comp-child>
</div>
</div>
What i have tried so far is:
in compParent TS:
export class compParentComponent{
@ViewChild(NgbDropdown) private readonly dropdown: NgbDropdown;
@HostListener('scroll', ['$event'])
closeAllDropdowns(event) {
this.dropdown.close();
}
}
But this.dropdown
returns undefined
and says close method is not a function associated with it. Also i tried to select all dropdowns using templateRef, that too didn't work.
Upvotes: 1
Views: 1580
Reputation: 4993
@ViewChild
and @ViewChildren
can only query elements from the component itself, not from childs. The possible option is to have a public reference to dropdown inside child, have reference to childs inside parent.
Parent:
export class CompParentComponent{
@ViewChildren(CompChild) compChild!: QueryList<CompChild>;
@HostListener('scroll', ['$event'])
closeAllDropdowns(event) {
this.compChild.forEach(dropdown => dropdown.close());
}
}
Child:
export class CompChildComponent{
@ViewChild(NgbDropdown) public dropdown: NgbDropdown;
}
Upvotes: 2