Is there a way to programmatically control a Bootstrap Dropdown in Angular?

Need help with opening and closing a Dropdown in my View using my typescript class. Any suggestions on how to achieve this?

Appreciate any assistance!

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

Answer №1

To access the dropdown from your TS file, you can utilize @ViewChild().

Include a template variable like #dropdown in the ngbDropdown element.

<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, in your typescript file, utilize @ViewChild(). This will allow you to 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();
  }
}

For a functional example, check out this Stackblitz link...

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The computed function is unable to find the property on the specified type

I am a beginner in TypeScript. I have encountered an issue with the code below, which runs perfectly fine in JavaScript but is not compiling here. export default { data: function() { return { data: [ 'Angular', 'A ...

MongoDB Node.js throws a RangeError when trying to push a message that exceeds the maximum call stack size

I'm currently delving into the world of building a MEAN app and encountering an issue when attempting to append a message to a messages array within my User Model. While I can successfully create a new message and pass the user object, I face an error ...

Preventing automatic download and storage of images and videos in an Ionic application

Currently, my chat application allows users to send and receive media such as photos and videos. However, when I open the message page, it automatically downloads and backs up all the media. I am looking to change this functionality on my Ionic page so th ...

Issue found in the file assert.d.ts located in the node_modules directory: Expected '{' or ';' at line 3, character 68. Error code: TS1144

When attempting to start the angular application with ng serve, I encountered an error. Below are the project details: Angular CLI: 8.2.0 Node: 14.19.1 OS: darwin x64 Angular: 8.2.0 ... animations, cli, common, compiler, compiler-cli, core, forms ... platf ...

An entire line of boxes has been checked off

Currently, I am working on adding an additional column with checkboxes to the Mat table example. However, I noticed that when I click on one checkbox in a column, the checkboxes in other columns also get selected. How can I implement this so that only th ...

Is it possible to use a single type predicate for multiple variables in order to achieve type inference?

Is there a way to optimize the repeated calls in this code snippet by applying a map to a type predicate so that TSC can still recognize A and B as iterables (which Sets are)? if(isSet(A) && isSet(B)) { ...

Understanding the tsconfig.json file in an Angular project

I encountered the following error in my tsconfig.ts file: 'No inputs were found in config file 'c:/Projects/Angular2//src/tsconfig.json'. Specified 'include' paths were '["src/**/*.ts"]' and 'exclude' paths ...

What is the most efficient way to execute useEffect when only one specific dependency changes among multiple dependencies?

My main objective is to update a state array only when a specific state (loadingStatus) undergoes a change. Yet, if I include solely loadingStatus as a dependency, React throws an error requesting all dependencies [loadingStatus, message, messageArray, set ...

Next.js does not support tooltips with custom children components

I created a unique Tooltip component and I'm attempting to include NextLink as the children. However, I encountered an error similar to the one below. Warning: Failed prop type: Invalid prop `children` supplied to `ForwardRef(Tooltip)`. Expected an e ...

Looking to retrieve the selected item from the list using console.log

Brief explanation: I am trying to retrieve the clicked item from a list using console.log(i.match). Please refer to my **home.html** code snippet below for how the list is dynamically generated. home.html <ion-card> <ion-card-content *ngFor="l ...

Is ngForIn a valid directive in Angular 4?

While attempting to loop over the properties of an object using *ngFor with in, I encountered a challenge. Here is a sample code snippet: @Controller({ selector: 'sample-controller', template: ` <ul> <li *ngFor="let i in o ...

Unable to organize list of entities based on numerical values

I am working with an array of objects structured like this: [ { "value": 351.68474, "o_p": [ "$.text" ] }, { "value": 348.0095, "o_p": [ ...

Excessive repetition in the style of writing for a function

When it comes to TypeScript, a basic example of a function looks like this: let myAdd: (x: number, y: number) => number = function ( x: number, y: number ): number { return x + y; }; Why is there redundancy in this code? I'm having trouble g ...

The 'log' property cannot be found on the type '{ new (): Console; prototype: Console; }' - error code TS2339

class welcome { constructor(public msg: string){} } var greeting = new welcome('hello Vishal'); Console.log(greeting.msg); I encountered an error at the Console.log statement. The details of the error can be seen in the image attached below. ...

The error message "TypeScript is showing 'yield not assignable' error when using Apollo GraphQL with node-fetch

Currently, I am in the process of implementing schema stitching within a NodeJS/Apollo/GraphQL project that I am actively developing. The implementation is done using TypeScript. The code snippet is as follows: import { makeRemoteExecutableSchema, ...

What is the best way to hand off a component to a helper function?

I am trying to create a helper function in TypeScript that takes a component as an argument and returns an array of objects, each containing a component node... // helpers.ts import { LINKS } from '../constants'; // error on the next line: Cannot ...

Having issues with a drop-down in Bootstrap. Is there anyone who can assist in getting it to function

I recently implemented a drop-down menu on the top navigation of my website. However, after applying Bootstrap to one of my pages, the drop-down menu stopped functioning properly. Below is the code that was applied: <link href="https://cdn.jsd ...

Is it possible to retrieve a static resource within server-side code in NextJs?

Exploring the static render feature of NextJS to generate a static version of my website has led me to ensure that all necessary data is provided for the initial page render. I have stored several blog posts as .md files in /static and aim to access them ...

Setting up Tarui app to access configuration data

I am looking to save a Tauri app's user configuration in an external file. The TypeScript front end accomplishes this by: import {appConfigDir} from "tauri-apps/api/path"; ... await fetch(`${await appConfigDir()}symbol-sets.json`) { ... ...

utilizing Typescript object within an array of objects

How can I optimize typing this nested array of objects? const myItem: Items[] = [{ id: 1, text: 'hello', items: [{ id: 1, text: 'world' }] }] One way to approach this is by using interfaces: interface It ...