2

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">

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

if you use a reference variable use in the way <div #dropdown="ngbDropdown" ngbDropdown class="d-inline-block"> (see that you indicate Angular that it's a ngbDropDown. So in .ts you can use @ViewChild('dropdown') dropdown -the {static:true}it's only in case your dropdown is always visible -not under a *ngIf-. When you use ViewChild, you can use also @ViewChild('dropdown', { read:NgbDropdown}). Futhermore, you can pass the dropdown as argument of one function in .html. e.g. (click)="doSomething(dropdown)" or even (click)="dropdown.toggle()"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.