Silas
Silas

Reputation: 69

How can I controll an Bootstrap Dropdown programmatically (Angular)

I have the following Dropdown in my View, and I wanna open/close it from my typescript class. How would I go on to do that?

Thanks for any help!

 <div ngbDropdown class="d-inline-block">
      <button class="btn" id="cartDropdown" ngbDropdownToggle>Warenkorb<img class="warenkorbNavbar"
          src="../assets/img/shopping-cart.png" /></button>
      <div ngbDropdownMenu aria-labelledby="cartDropdown">

Upvotes: 2

Views: 2138

Answers (1)

Jason White
Jason White

Reputation: 5813

You can access the dropdown from within the TS file by using @ViewChild().

Add a template variable to the ngbDropdown for example #dropdown

<div #dropdown ngbDropdown class="d-inline-block">
  <button class="btn btn-outline-primary" id="dropdownBasic1" ngbDropdownToggle>Toggle dropdown
  </button>
  <div ngbDropdownMenu aria-labelledby="dropdownBasic1">
    <button ngbDropdownItem>Action - 1</button>
    <button ngbDropdownItem>Another Action</button>
    <button ngbDropdownItem>Something else is here</button>
  </div>
</div>

Then use @ViewChild() in your typescript file. You can then call the open method on the dropdown from within the typescript

@Component({
  selector: 'ngbd-dropdown-basic',
  templateUrl: './dropdown-basic.html',
})
export class NgbdDropdownBasic {
  @ViewChild(NgbDropdown, { static: true })
  public dropdown: NgbDropdown;

  public toggleDropdown(): void {
    this.dropdown.open();
  }
}

A working Stackblitz example...

https://stackblitz.com/edit/angular-7vbmva

Upvotes: 3

Related Questions