angular2 ng-bootstrap drop down dropdown component
Can some one help me to find out how can i bind angular2 component with dropdown and call open or close method..
they don't have much documentation.
You can use ViewChild decorator. In parent component it should look something like that:
import 'ViewChild' from '@angular/core'
import 'NgbDropdown' from '...';
[...]
export class ParentComponent {
@ViewChild(NgbDropdown)
private dropdown: NgbDropdown;
closeDropdown() {
this.dropdown.close();
}
}
You can read more about ViewChild in official documentation: Component Interaction | ViewChild.
The easiest way to achieve this would be to use an exported instance of the NgbDropdown
directive. It can be done as follows (notice #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>
As soon as you do the above you can invoke documented (https://ng-bootstrap.github.io/#/components/dropdown) methods on the NgbDropdown
directive instance. The available methods are: open
, close
, toggle
and isOpen
. You can invoke them as follows (example to open a dropdown from "outside"):
<button (click)="myDrop.open()">
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>
Angular
make sure to import ViewChild and NgbDropdown
import { NgbDropdown } from '@ng-bootstrap/ng-bootstrap';
import { ViewChild } from '@angular/core';
@ViewChild('myDrop', { static: true }) myDrop: NgbDropdown;
closeDropdown() {
this.myDrop.close();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With