Question:
I have started an app with angular-cli and I have installed bootstrap 4. When inserting a navbar in app.component.html everything was apparently correct but when minimizing to mobile size the hamburger button appears but the menu is not displayed.
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Pricing</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#">Disabled</a>
</li>
</ul>
</div>
</nav>
Answer:
Bootstrap is a library that adds styles on the one hand and (optionally) behavior on the other. The problem is that the behavior is added using jQuery and it doesn't work well when you mix it with frameworks like Angular, AngularJS, React… etc because components have their own life cycle and appear and disappear without jQuery knowing about it.
Therefore the most direct solution is to create a TopNav component and add the desired behavior to it, something like:
export class TopNavComponent {
show:boolean = false;
// otro código que necesites
toggleCollapse() {
this.show = !this.show
}
}
with a template (template) similar to:
<button (click)="toggleCollapse()" class="navbar-toggler navbar-toggler-right" type="button">
<!-- otras cosas -->
<div class="collapse" [class.show]="show">
<!-- elementos del menú/barra -->
</div>
This is just a very simple sketch of the idea, without taking into account that depending on the size of the screen the presentation varies (on a PC you would not see the button and the variable show
should be true
all the time), but I think what can you do to the idea.