Web
Analytics
Build a responsive Bootstrap 4 Navbar in Angular 5 without jQuery | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

Build a responsive Bootstrap 4 Navbar in Angular 5 without jQuery

In this blog, I am demonstrating that how we can create collapsible navbar using Bootstrap and in angular 5 projects without using jquery and popper.js which are also not recommended by angular. To demonstrate it I have created header component where we will create a collapsible navbar of Bootstrap 4 and we will implement collapsible effect without using jQuery.js and popper.js.

Step 1:  installation of Bootstrap 4 and passing the reference of bootstrap into styles.css

npm install --save bootstrap

// Pass reference of bootstrap 4 into styles.css

@import "../node_modules/bootstrap/dist/css/bootstrap.css"




Step 2: Create new angular header component

ng g c header --is --it

Step 3: Update index.html 

  <div class="container-fluid"></div>
  <app-root></app-root>
</div>

Step 4: Add the following code into header.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-header',
  template: `
  <nav class="navbar navbar-expand-lg navbar-light bg-light">
  <button class="navbar-toggler" type="button" (click)="toggleNavbar()"  data-toggle="collapse" data-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarTogglerDemo01" [ngClass]="{ 'show': navbarOpen }">
    <a class="navbar-brand" href="#">Hidden brand</a>
    <ul class="navbar-nav mr-auto mt-2 mt-lg-0">
      <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="#">Link</a>
      </li>
      <li class="nav-item">
        <a class="nav-link disabled" href="#">Disabled</a>
      </li>
    </ul>
    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
    </form>
  </div>
</nav>
  `,
  styles: []
})
export class HeaderComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }
  navbarOpen = false;

  toggleNavbar() {
    this.navbarOpen = !this.navbarOpen;
  }


}

in the above code, I am using show attribute and NGclass directive of angular to manipulate Dom element of collapsable navbar here I am changing the show attribute using custom property navbarOpen and event binding using (click) button event.

Step 5: Run and see the results

ng serve --open

Output

angular bootstrap 4