Click the button to open the drop-down menu
P粉232409069
2023-09-04 15:04:13
<p>I am using bootstrap 5 cdn and I want to open the dropdown without clicking on the dropdown. </p>
<p>I use the navigation bar and want to display "drop-down links": </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>In the component I try to do the following but it doesn't work: </p>
<pre class="brush:php;toolbar:false;">export class AppComponent {
open() {
const dropdown = document.getElementById('test');
dropdown.click();
}
}</pre>
<p>I did it in stackblitz: test</p>
Add bootstrap attributes to button:
Link code: https://stackblitz.com/edit/angular-bootstrap-5-dynamic-navbar-77sj13?file=app/app.component.html
It will work, however. Keep in mind that your angular application should control these elements, so mixing external libraries with framework libraries (Angular, Vue, React) will always cause trouble
For this purpose, there are special implementations, for example: https://ng- bootstrap.github.io/#/home Angle guide
Another option is to use ngIf to show the navigation bar (no animation by default)
Another link: https://stackblitz.com/edit/angular-bootstrap-5-dynamic-navbar-hygpzq?file=app/app.component.html