angular 如何从父组件触发 ngbDropdown 方法?

How to trigger ngbDropdown methods from parent component in angular?

我在 angular 应用程序中使用 NgbDropdown。我有两个组件 CompParentCompChild。其中 compChild 包含下拉列表的 HTML 并且包含在 CompParent 中。 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>

并且 CompChild 包含在 CompParent 中,如下所示:

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>

到目前为止我尝试过的是:

compParent TS:

export class compParentComponent{

  @ViewChild(NgbDropdown) private readonly dropdown: NgbDropdown;

  @HostListener('scroll', ['$event'])
  closeAllDropdowns(event) {
    this.dropdown.close();
  }

}

但是 this.dropdown returns undefined 并说 close 方法不是与其关联的函数。我还尝试 select 使用 templateRef 的所有下拉菜单,那也没用。

@ViewChild@ViewChildren只能从组件本身查询元素,不能从child中查询。可能的选择是在 child 中引用 public 下拉列表,在 parent.

中引用 childs

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;

}