Navbar toggle not working with Angular 4 / ng-bootstrap

Braste84 picture Braste84 · Sep 21, 2017 · Viewed 11.6k times · Source

I am using ng-bootstrap in my angular 4 project:

<navbar class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
    <button aria-controls="navbarsDefault" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler navbar-toggler-right" data-target="#navbarsDefault" data-toggle="collapse" type="button">
        <span class="navbar-toggler-icon"></span>
    </button>
    <a class="navbar-brand" href="#">Navbar</a> 
    <div class="collapse navbar-collapse" id="navbarsDefault">
        <ul class="navbar-nav mr-auto">
            <li class="nav-item">
                <a class="nav-link active" routerlink="/dashboard" routerlinkactive="active" ng-reflect-router-link="/dashboard" ng-reflect-router-link-active="active" href="/dashboard">Dashboard</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" routerlink="/program" routerlinkactive="active" ng-reflect-router-link="/program" ng-reflect-router-link-active="active" href="/program">Programm</a>
            </li>          
        </ul>
    </div>
</navbar>

The navbar is there, it is responsive, it seems to work fine. But the navbar-toggler button does not toggle the navbar, when it is collapsed and i can't find an error.

Answer

jmiguel77 picture jmiguel77 · Oct 3, 2017

I ended up doing something like this:

In the html template i have this code:

 <nav id="mainNavbar" class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
        <a class="navbar-brand" href="#">Navbar</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse"
           data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent"
           aria-expanded="false" aria-label="Toggle navigation"
           (click)="toggleCollapsed()">
          <span class="navbar-toggler-icon"></span>
        </button>
        <div id="navbarSupportedContent" [ngClass]="{'collapse': collapsed, 'navbar-collapse': true}">
            ......
        </div>
</nav>

In the component I have this

export class NavComponent {
     collapsed = true;
     toggleCollapsed(): void {
       this.collapsed = !this.collapsed;
     }
}