Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-bootstrap example calling method from component

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.

like image 909
d-man Avatar asked Sep 20 '16 21:09

d-man


3 Answers

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.

like image 103
Mateusz Witkowski Avatar answered Nov 13 '22 08:11

Mateusz Witkowski


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()">
like image 45
pkozlowski.opensource Avatar answered Nov 13 '22 08:11

pkozlowski.opensource


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();
}
like image 26
Jubin Avatar answered Nov 13 '22 09:11

Jubin