Determine Toggle State in Multiple Ng-Bootstrap Dropdowns in Angular

After receiving a helpful response to my recent question, I have encountered another issue.

This time, I am wondering: How can I determine the toggle status in an ng-bootstrap dropdown when multiple dropdowns are present?

Attempting to do so only provides the status of the first dropdown. Since there is no unique id containing the 'isopen()' method, I find myself stuck.

Any suggestions on how to detect the toggle status in ng-bootstrap dropdowns with multiple instances?

Answer №1

why not utilize (openChange) instead???? Check out this StackBlitz example

<div #drop1 ngbDropdown (openChange)="checkDropDown($event,1)">
  <button class="btn btn-outline-primary" ngbDropdownToggle >Toggle-1</button>
  <div ngbDropdownMenu aria-labelledby="dropdownConfig">
    <button ngbDropdownItem>Action - 1</button>
    <button ngbDropdownItem>Another Action</button>
    <button ngbDropdownItem>Something else is here</button>
  </div>
</div>

If we want to reference the dropdown element, we can do so like this

<div #drop1="ngbDropdown" 
      ngbDropdown (openChange)="checkDropDown($event,drop1)">
....
</div>
checkDropDown(open:boolean,dropdown: NgbDropdown) {
    console.log(open,dropdown.placement)

}

UPDATE: For detailed information about ngbDropdown, refer to the official documentation here. The API may be complex, so let's summarize it succinctly.

Inputs are properties that can be added in .html as shown below

<div ngbDropdown [propertie]="variable"..>
//or
<div ngbDropdown propertie="value" ...>
//if it's a string, remember to use single quotes e.g.
<div ngbDropdown autoClose="'outside'" ...>

Outputs represent "events", and if they return a value, we capture the response using $event, for example

<div ngbDropdown (openChange)="myFunction($event)" ...>
//If additional arguments need to be sent, simply add them
<div ngbDropdown (openChange)="myFunction($event,"some more")" ...>

Methods are functions that can be used in the .ts file if we have ViewChild or ViewChildren defined

<div #myngbDropdown ngbDropdown [propertie]="variable"..>

@ViewChild('myngbDropDown') mydrop:nhbDropDown;

ngOnAtferView()
{
    console.log(this.mydrop.isOpen())
}

Answer №2

If I were to handle this situation, my approach would look something like the following:

To start, I would retrieve all the dropdowns using the ViewChildren decorator

@ViewChildren(NgbDropdown)
dropdowns: QueryList<NgbDropdown>;
dropdown: NgbDropdown;

Next, I would modify the checkDropDown method as shown below:

checkDropDown(dropdown: any) {
  // Identify which dropdown was clicked
  this.dropdown = this.dropdowns.find(x => (x as any)._elementRef.nativeElement == dropdown)
  // Determine if the clicked dropdown is open
  console.log(this.dropdown.isOpen())
}

Additionally, it is necessary to make changes in your HTML file by utilizing template ref:

<div #drop1 ngbDropdown>
<button class="btn btn-outline-primary" ngbDropdownToggle (click)="checkDropDown(drop1)">Toggle-1</button>

...

<div #drop2 ngbDropdown>
<button class="btn btn-outline-primary" ngbDropdownToggle (click)="checkDropDown(drop2)">Toggle-2</button>

I have also provided a functional StackBlitz for reference.

By the way, please note that your buttons share the same ids, so you might want to remove them: dropdownConfig

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

Error: The property 'attach' of undefined is not readable in makeStyles.js

Encountering a series of type errors when attempting to access the Login component of my MERN app on the production version, as shown in this image: https://i.sstatic.net/6apXu.png The app (https://github.com/ahaq0/kumon_schedule) functions perfectly on ...

Streamline the process of sorting through 2 arrays

Is there a more concise and elegant way to achieve the same functionality as my current method? I am looking for a shorter solution to create an array of items that haven't been used in the form previously, which are then used to populate a select dro ...

What is the best way to use identical styles for 2 different classes at separate breakpoints?

Is it possible to apply a chunk of (S)CSS to two different elements in two different breakpoints to avoid redundancy? I am using Bootstrap 4.6. <div class="one"> <div class="content">Something</div> </div> & ...

What causes bootstrap columns to wrap to a new line when in print view mode?

<!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> </head> <body> <div class="container-fluid"> <div class="conta ...

Is there a way to retrieve all values in the pathname from a URL after the initial slash

Extracting pathname pathname: "/kids/dlya-malyshey/platya-i-yubki" By using the substr function, I will remove the initial slash location.pathname.substr(1,); Now, the result is kids/dlya-malyshey/platya-i-yubki The challenge is to extract all ...

What sets Angular 2 Components apart from traditional Web Components?

There seems to be some confusion here. Is it possible for an Angular 2 Component to be utilized outside of its Angular scope similar to a Web Component? Or is there more to it than meets the eye? ...

The React-Typescript error message is stating that the module "react-router-dom" does not have the exported member "RouteComponentProps"

I encountered an issue with my project involving a login page and the usage of "RouteComponentProps". Unfortunately, I received the following error: Module '"react-router-dom"' has no exported member 'RouteComponentProps'. Upon attempt ...

Troubleshooting a cross-component property problem involving a fetch request within a subscription

My current objective is to utilize ActivatedRoute parameters to make a fetch request and update a class property with the fetched data. Progress has been made on making the request, but I am facing difficulties in getting the fetched data to the specific c ...

Attempting to grasp the concept of implementing FormArray

When I execute the following code: this.formArray = new FormArray([ new FormControl(''), new FormControl(''), ]); formControlA() { return this.formArray.at(0); } formControlB() { return this.formArray.at(1); } and then use it ...

The definition of "regeneratorRuntime" is missing in the rete.js library

After encountering a problem, I managed to find a potential solution. My current challenge involves trying to implement Rete.js in Next.js while using Typescript. The specific error message that's appearing is: regeneratorRuntime is not defined Be ...

What is the process for upgrading TypeScript to the newest version using npm?

My current TypeScript version on my machine is 1.0.3.0 and I am looking to upgrade it to the latest version, which is 2.0. Could someone please guide me on how to accomplish this using npm? ...

What are some effective methods for drawing attention to newly added table rows?

Whenever I input new data into my table, the data does not get highlighted as expected. However, the existing data in the table gets highlighted with no issues. Can you please help me troubleshoot why my code is not functioning correctly? Thank you. The f ...

Unable to determine the appropriate signature for calling the date function

<td> {{ fundInfo.startDate | date: "yyyy-MM-dd" }} </td> The issue is located in the primeng-test-b.component.html file under src\app\primeng-test-b directory. ...

Pressing a button will reset the input spinner in Bootstrap

Is there a way to reset the bootstrap input spinner by clicking a button? I attempted using document.getelementbyId().value = "0" and also tried using reset(), but neither method worked. Any suggestions on how to successfully reset it? function resetScor ...

The issue of ExpressionChangedAfterItHasBeenCheckedError is a common problem faced by Angular

I have implemented a component loading and an interceptor to handle all requests in my application. The loading component is displayed on the screen until the request is completed. However, I am encountering an error whenever the component inside my router ...

What is the correct way to set the default function parameter as `v => v` in JavaScript?

function customFunction<T, NT extends Record<string, string | number | boolean>>( data: T, normalize?: (data: T) => NT, ) { const normalizedData = normalize ? normalize(data) : {}; return Object.keys(normalizedData); } customFuncti ...

The loop in Typescript is malfunctioning

Having an issue while trying to iterate over an array in Angular. Despite initializing and filling the array, the loop doesn't seem to work as expected. The array is populated in the following manner. It is logged in the console to confirm that it ha ...

include the ReactToastify.css file in your project using the import statement

Error in file path C:\Users\User\Documents\GitHub\zampliasurveys_frontend\node_modules\react-toastify\dist\ReactToastify.css:1 ({"Object.":function(module,exports,require,__dirname,__filename,jest){:ro ...

Continue running the code after a function has completed its execution in Angular 4

My function uses web3.js to generate a new account and retrieve the account address. Here is my service implementation: @Injectable() export class ContractsService { private web3: any; public acc_no: any; public createAccount(): any { this.we ...

Obtaining the TemplateRef from any HTML Element in Angular 2

I am in need of dynamically loading a component into an HTML element that could be located anywhere inside the app component. My approach involves utilizing the TemplateRef as a parameter for the ViewContainerRef.createEmbeddedView(templateRef) method to ...