答案 0 :(得分:5)
实现此目标的最简单方法是使用NgbDropdown
指令的导出实例。它可以按如下方式完成(注意#myDrop="ngbDropdown"
):
<div ngbDropdown #myDrop="ngbDropdown">
<button class="btn btn-outline-primary" id="dropdownMenu3" ngbDropdownToggle>Toggle</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenu3">
<button class="dropdown-item">Action - 1</button>
<button class="dropdown-item">Another Action</button>
<button class="dropdown-item">Something else is here</button>
</div>
</div>
只要执行上述操作,就可以在NgbDropdown
指令实例上调用记录的(https://ng-bootstrap.github.io/#/components/dropdown)方法。可用的方法有:open
,close
,toggle
和isOpen
。您可以按如下方式调用它们(例如从“外部”打开下拉列表):
<button (click)="myDrop.open()">
答案 1 :(得分:5)
HTML
<div ngbDropdown #myDrop="ngbDropdown">
<button class="btn btn-outline-primary" id="dropdownMenu3"
ngbDropdownToggle>Toggle</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenu3">
<button class="dropdown-item" (click)="closeDropdown()">Close Dropdown</button>
</div>
</div>
角度
确保导入ViewChild和NgbDropdown
import { NgbDropdown } from '@ng-bootstrap/ng-bootstrap';
import { ViewChild } from '@angular/core';
@ViewChild('myDrop', { static: true }) myDrop: NgbDropdown;
closeDropdown() {
this.myDrop.close();
}
答案 2 :(得分:4)
您可以使用ViewChild装饰器。在父组件中,它看起来应该是这样的:
import 'ViewChild' from '@angular/core'
import 'NgbDropdown' from '...';
[...]
export class ParentComponent {
@ViewChild(NgbDropdown)
private dropdown: NgbDropdown;
closeDropdown() {
this.dropdown.close();
}
}
您可以在官方文档中了解有关ViewChild的更多信息:Component Interaction | ViewChild。
答案 3 :(得分:1)
我尝试了上面的方法,但它似乎没有执行任何操作,因此我进行了一些反复试验,发现为什么当我打电话给myDrop.open()
时什么都没发生。您必须将[autoClose]="false"
添加到具有下拉引用的元素中。
<div ngbDropdown #myDrop="ngbDropdown" [autoclose]="false">
<button class="btn btn-outline-primary" id="dropdownMenu3" ngbDropdownToggle>Toggle</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenu3">
<button class="dropdown-item">Action - 1</button>
<button class="dropdown-item">Another Action</button>
<button class="dropdown-item">Something else is here</button>
</div>
</div
//Somewhere else
<button (click)="myDrop.open()"> // or pass the reference as a parameter to call it
in a function.
答案 4 :(得分:0)
如果你需要将ngbDropdown实例传递给另一个组件,如上所述,将该实例定义为模板引用变量#myDrop="ngbDropdown"
,然后在要访问该下拉列表实例的组件上声明一个属性。输入装饰器,如
@Component({
selector: 'my-component',
template: `<button (click)=closeMyDrop()">Close myDrop</button>`
})
export class MyComponent {
@Input() myDrop;
closeMyDrop(){
this.myDrop.close();
}
}
然后在使用子组件的父组件中,为模板引用变量定义myDrop
的属性,如:
<my-component [myDrop]="myDrop"></my-component>
Angular 2 Documentation for template reference variables
Angular 2 Documentation for passing data from parent to child with input binding