You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何默认展开NG Bootstrap下拉菜单?附相关实现代码

How to Make NG Bootstrap Dropdown Open by Default

Hey, I’ve dealt with this exact need for NG Bootstrap dropdowns before—here are two reliable approaches to get your dropdown expanded by default:

1. Use the NgbDropdown Component API (Flexible for Dynamic Control)

This method gives you more control if you need to toggle the dropdown later based on events or state changes.

First, add a template reference variable to your dropdown container and mark it as an ngbDropdown:

<img src="assets/images/small-images/1.png" width="32px" id="dropdownForm1" ngbDropdownToggle>
<!-- Add #dropdownRef="ngbDropdown" to the dropdown menu container -->
<div #dropdownRef="ngbDropdown" ngbDropdownMenu aria-labelledby="dropdownForm1" style="width: 200px; border-radius: 0px; margin-top: 28px;">
  <app-mega-menu></app-mega-menu>
</div>

Then, in your component class, use ViewChild to grab this reference and call the open() method when the component initializes:

import { Component, ViewChild, OnInit } from '@angular/core';
import { NgbDropdown } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'your-component-selector',
  templateUrl: './your-component.component.html'
})
export class YourComponent implements OnInit {
  // Reference the dropdown from the template
  @ViewChild('dropdownRef') private dropdown!: NgbDropdown;

  ngOnInit(): void {
    // Open the dropdown when the component loads
    this.dropdown.open();
  }
}

2. Use the [open] Input Property (Quick Static Solution)

If you just need the dropdown to always be open by default with no dynamic control required, this is the simplest fix. Just bind the open input to true:

<img src="assets/images/small-images/1.png" width="32px" id="dropdownForm1" ngbDropdownToggle>
<div [open]="true" ngbDropdownMenu aria-labelledby="dropdownForm1" style="width: 200px; border-radius: 0px; margin-top: 28px;">
  <app-mega-menu></app-mega-menu>
</div>

Quick Notes:

  • If you use the [open]="true" approach and later want to toggle the dropdown manually, bind it to a component property (like isDropdownOpen = true) instead of a hardcoded value—this lets you update the state as needed.
  • Double-check that you’ve imported NgbDropdownModule in your Angular module to avoid runtime errors.

内容的提问来源于stack exchange,提问作者Mykel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:56:35