单击按钮打开下拉菜单
P粉232409069
2023-09-04 15:04:13
<p>我正在使用 bootstrap 5 cdn,我想打开下拉列表而不单击下拉列表。</p>
<p>我使用导航栏并希望显示“下拉链接”:</p>
<pre class="brush:php;toolbar:false;"><nav class="navbar navbar-expand-sm navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
<button
class="navbar-toggler"
type="button"
data-bs-toggle="collapse"
data-bs-target="#navbarNavDropdown"
aria-controls="navbarNavDropdown"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavDropdown">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item dropdown">
<a
class="nav-link dropdown-toggle"
href="#"
id="test"
role="button"
data-bs-toggle="dropdown"
aria-expanded="false"
>
Dropdown link
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<li><a class="dropdown-item" href="#">Action</a></li>
<li><a class="dropdown-item" href="#">Another action</a></li>
<li><a class="dropdown-item" href="#">Something else here</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<button class="btn btn-primary btn-sm" (click)="open()">Abrir</button></pre>
<p>在组件中我尝试执行以下操作,但它不起作用:</p>
<pre class="brush:php;toolbar:false;">export class AppComponent {
open() {
const dropdown = document.getElementById('test');
dropdown.click();
}
}</pre>
<p>我在 stackblitz 中做到了:测试</p>
向按钮添加引导属性:
链接代码:https://stackblitz.com/edit/angular-bootstrap-5-dynamic-navbar-77sj13?file=app/app.component.html
它会起作用,但是。请记住,您的角度应用程序应该控制这些元素,因此将外部库与框架库(Angular、Vue、React)混合使用总是会引起麻烦
对于这种用途,有特殊的实现,例如: https://ng- bootstrap.github.io/#/home 角度引导
另一个选项是使用 ngIf 显示导航栏(默认情况下没有动画)
另一个链接: https://stackblitz.com/edit/angular-bootstrap-5-dynamic-navbar-hygpzq?file=app/app.component.html