Close several dropdowns at once with ng-bootstrap

Within my Angular app, there are two dropdowns that I have integrated:

<div class="input-group">
  <input
    id="startDate"
    type="text"
    class="form-control"
    aria-label="Start date"
    dlDateTimeInput
    [ngModel]="startDate"
  />
  <div ngbDropdown class="d-inline-block">
    <div class="input-group-append">
      <button
        class="btn btn-outline-primary"
        id="startDateDropdown"
        ngbDropdownToggle
      >
        <i class="oi oi-calendar"></i>
      </button>
      <div ngbDropdownMenu aria-labelledby="startDateDropdown">
        <div style="width: 360px">
          <dl-date-time-picker
            [(ngModel)]="startDate"
            (change)="startDateSelected($event)"
            minuteStep="15"
          >
          </dl-date-time-picker>
        </div>
      </div>
    </div>
  </div>
</div>
<div class="input-group">
  <input
    id="endDate"
    type="text"
    class="form-control"
    aria-label="End date"
    dlDateTimeInput
    [ngModel]="endDate"
  />
  <div ngbDropdown class="d-inline-block">
    <div class="input-group-append">
      <button
        class="btn btn-outline-primary"
        id="endDateDropdown"
        ngbDropdownToggle
      >
        <i class="oi oi-calendar"></i>
      </button>
      <div ngbDropdownMenu aria-labelledby="endDateDropdown">
        <div style="width: 360px">
          <dl-date-time-picker
            [(ngModel)]="endDate"
            (change)="endDateSelected($event)"
            minuteStep="15"
          >
          </dl-date-time-picker>
        </div>
      </div>
    </div>
  </div>
</div>

I've been attempting to resolve the issue of closing the dropdown menu using this code snippet:

import { ViewChild } from "@angular/core";
import { NgbDropdown } from "@ng-bootstrap/ng-bootstrap";

[...]

export class ParentComponent {
  
  @ViewChild(NgbDropdown)
  private dropdown: NgbDropdown;

  public startDateSelected(event: DlDateTimePickerChange<Date>): void {
    this.startDatePicked.emit(event.value);
    this.dropdown.close();
  }

  public endDateSelected(event: DlDateTimePickerChange<Date>): void {
    this.endDatePicked.emit(event.value);
    this.dropdown.close();
  }
}

The Issue at Hand

The predicament lies in the fact that only the first dropdown closes while the second remains open.

How can one go about simultaneously closing both the start and end dropdowns?

Answer №1

To collapse all dropdown menus, you should utilize ViewChildren instead of ViewChild. This function will retrieve a collection of all elements or directives that match the specified selector.

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

startDateSelected(event: DlDateTimePickerChange<Date>): void {
  this.startDatePicked.emit(event.value);
  this.closeDrownDowns();
}

endDateSelected(event: DlDateTimePickerChange<Date>): void {
  this.startDatePicked.emit(event.value);
  this.closeDrownDowns();
}

private closeDropDowns() {
  this.dropdowns?.forEach(x => x.close());
}

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

Angular 6 ActivatedRoute Parameters

I'm having trouble retrieving the data of each record using ActivatedRoute. I've been able to get the ID for each one, but I can't seem to access the other data. Any suggestions? Check out my stackblitz example: https://stackblitz.com/edit/ ...

`Angular Image Upload: A Comprehensive Guide`

I'm currently facing a challenge while attempting to upload an image using Angular to a Google storage bucket. Interestingly, everything works perfectly with Postman, but I've hit a roadblock with Angular Typescript. Does anyone have any suggesti ...

Tips for managing update logic in the server side with sveltekit

Currently, I am using Sveltekit and I am facing a dilemma regarding updating input data. The actual update process is straightforward, but there is an issue that arises when trying to send an update API request immediately, as it requires an accessToken to ...

Challenges arise when trying to access environment variables using react-native-dotenv in React

I am currently working on two separate projects, one being an app and the other a webapp. The app project is already set up with react-native-dotenv and is functioning as expected. However, when I attempt to use the same code for the webapp, I encounter an ...

Fetching JSON data from a Node.js server and displaying it in an Angular 6 application

Here is the code snippet from my app.js: app.get('/post', (req,res) =>{ let data = [{ userId: 10, id: 98, title: 'laboriosam dolor voluptates', body: 'doloremque ex facilis sit sint culpa{ userId: 10' ...

What could be the reason for my Angular 2 app initializing twice?

Can someone help me figure out why my app is running the AppComponent code twice? I have a total of 5 files: main.ts: import { bootstrap } from '@angular/platform-browser-dynamic'; import { enableProdMode } from '@angular/core'; impor ...

Problem encountered with ESLint when utilizing babel module-resolver in conjunction with TypeScript

Typescript is not making type inferences with resolved imports, but it does with relative imports. Any assistance would be greatly appreciated. https://i.sstatic.net/2pgHX.png When using the 'useTheme' function, an error is displayed: "U ...

Pass the chosen value from an Angular material select component to a specified function

I'm having trouble figuring out how to pass the selected value to a function in a mat-select without using ngModel. In the desktop version of my app, I have a list with clickable items, but on the iPad version, I am using a mat-select element. In the ...

Creating a nested structure for dynamic data in Angular

I'm facing an issue while attempting to create a flexible structure dynamically. I possess the following string. "Client->Plant->Route->Turn" I have an array of devices with values for each field in the string along with extra information, ...

Tips on utilizing a function that was generated within the constructor

I'm currently in the process of developing a function within the constructor, and it is essential that this function be placed inside the constructor. I am interested in implementing a button to trigger this function from an external source, but unfor ...

Adjust the height of the rows in the column to match the height of the parent

I'm struggling to figure out how to make the child content fill the height of a column. I've tried using Bootstrap grid system and flex utilities. The only solution that somewhat worked was setting the row height to 50%, but the issue is, I don& ...

Error encountered while retrieving the cropped image, atob function was unable to execute

I am currently facing an issue with saving a cropped image in Chrome. When I try to save it, the download fails when using the Download button that I added to the page. I have successfully used ngx-image-cropper for cropping the image as intended. The cro ...

Bootstrap / Blazor - no action when clicking on an image link

Having issues with adding a simple HTML link around an image in my Bootstrap 4.5 / Blazor app. When I click on the link, nothing happens. How is this possible? I've tried using the <a href"..."><img ...> pattern, as well as NavL ...

Poor mapping on Google Maps API

I've been trying to embed a Google Maps on my website, but for some reason, it keeps stretching and showing grey sections with rounded borders. Here's the code I'm using: <div class="p-5 col-6 d-flex flex-column justify-content-between"& ...

What's the best way to fix a div to the bottom left corner of the screen?

I have explored various solutions regarding this issue, but none of them seem to meet my specific requirements. What I am trying to achieve is the correct positioning of a div as depicted in the green area in the image. https://i.sstatic.net/O9OMi.png Th ...

Angular JWT token validation error

I am currently experiencing an issue with the Angular JWT token. It works perfectly fine on my API when tested using Postman, but for some reason it is not working when called from Angular. Here are the request details: https://i.sstatic.net/L6Tsr.png I c ...

What is the best way to delay a recursive JavaScript function for 3 seconds?

Before writing this post, I have already come across the following questions: how-to-pause-a-settimeout-call how-to-pause-a-settimeout-function how-to-pause-a-function-in-javascript delay-running-a-function-for-3-seconds Question The below code snipp ...

Generate a new Angular2 component on the fly based on information retrieved from an API request

Within my application, I have implemented a dropdown menu featuring 'Statements' that users can select. Upon the selection of a specific statement, an API call is triggered to fetch data on how this information should be displayed, referred to as ...

Merging classes from several files into a unified namespace in typescript

When working with typescript, my goal is to instantiate a class by using its name as a string. After some research, I discovered the following approach: const googlecommand = Object.create((Commands as any)['GoogleCommand'].prototype); This lin ...

Leveraging Bootstrap in Django with Django_tables2

What steps should be taken to integrate Bootstrap with django-tables2? Do I need to specify DJANGO_TABLES2_TEMPLATE = 'django_tables2/bootstrap4.html' somewhere? If I want to utilize bootstrap5 instead, what changes do I need to make? ...