Blog

Build a Responsive Navbar Using Angular 5 and Bootstrap 4

A Responsive Nav Bar

A UI that is responsive to device and browser size is critical to provide usable access to your website and services.  One of the most important parts of the UI is the navigation bar (navbar), which allows users to easily find and access information. The good news is that building a responsive navbar is not difficult, and we are going to show you how. In this edition of Ping, we will demonstrate how to set up a responsive navbar using Angular 5 and Bootstrap 4.

Introduction

This tutorial will use the Angular quickstart template, onto which we will add a navbar component to the top.

For this tutorial you need to have Node, Angular CLI, and Yarn installed. If you don’t have these, the following links will help you get started:

First, let’s create the project using Angular CLI. The following command will create the Angular project in a new folder called angular-bootstrap-scalable-navbar and default the style sheet format to scss.

>ng new angular-bootstrap-scalable-navbar --style scss

Next change directory to the new project and install the yarn packages

>yarn add bootstrap
>yarn add@ng-bootstrap/ng-bootstrap@1.1.2

Code

The following will discuss the code we add to put the navbar in place.

Open styles.scss and add the following line.

@import"~bootstrap/scss/bootstrap";

Next open app.module.ts and add the following to the top of the file in the import statements:

import{ NgbModule}from"@ng-bootstrap/ng-bootstrap";
import{ BrowserModule }from'@angular/platform-browser';
import{ NgModule }from'@angular/core';
import{ NgbModule}from"@ng-bootstrap/ng-bootstrap";

And add NgbModule.forRoot() to the import section of @NgModule as seen below:

@NgModule({
 declarations: [
 AppComponent,
 NavbarComponent
 ],
 imports: [
 BrowserModule,
 NgbModule.forRoot(),
 ],
 providers: [],
 bootstrap: [AppComponent]
})

The Navbar Component

To create the navbar component we will use Angular CLI to generate the scaffolding and set up the component configuration.

On the command line, in the project folder, run the following command

>ng g navbar

Looking back at the project we can see the navbar folder created in src/app/. Looking back at app.module.ts we can see that the navbar component has been configured for use on the project.

Lets now add the navbar to the angular index file. Open ‘src/app/app.component.html’ wrap the existing code in a div with the attribute class=’container’. Next add <app-navbar></app-navbar> above the div we just added. Your code should look something like this:

<!--The content below is only a placeholder and can be replaced.-->
<app-navbar></app-navbar>
<div class="container">
 <div style="text-align:center">
 <h1>
 Welcome to {{ title }}!
 </h1>
 <img width="300"alt="Angular Logo"
src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">
 </div>
 <h2>Here are some links to help you start: </h2>
 <ul>
 <li>
 <h2><a target="_blank" rel="noopener" href="https://angular.io/tutorial">Tour of Heroes</a></h2>
 </li>
 <li>
 <h2><a target="_blank" rel="noopener" href="https://github.com/angular/angular-cli/wiki">CLI Documentation</a>
 </h2>
 </li>
 <li>
 <h2><a target="_blank" rel="noopener" href="https://blog.angular.io/">Angular blog</a></h2>
 </li>
 </ul>
</div>

The <app-navbar> directive tells angular to insert the navbar component. If you look at src/app/navbar/navbar.component.ts, you will see that the navbar component is linked to this directive in the @Component directive using the attribute selector.

We are wrapping the main content in a div with the class ‘container’ to tell bootstrap to add a margin to the main page, where the navbar will scale across the entire page.

navbar.component.html

Let’s use the links in the template to create the navigation piece of the navbar. Change your code to look like the following. After the code block, we will detail what we have done.

<div class="main">
 <div class="container">
 <div class="row">
 <div class="col-md-12">
 <nav class="navbar navbar-expand-md navbar-blue">
 <a>
 <span class="site-name">Angular Bootstrap</span>
 </a>
 <button class="navbar-toggler ml-auto custom-toggler"type="button"data-toggle="collapse"
(click)="isCollapsed= !isCollapsed">
 <span class="navbar-toggler-icon"></span>
 </button>

 <!-- The menu items -->
 <!--<div class="collapse navbar-collapse" id="navbarSupportedContent">-->
<div class="collapse navbar-collapse"[ngbCollapse]="isCollapsed"id="navbarSupportedContent">
 <ul class="navbar-nav ml-auto">
 <li class="navbar-link"><a class="text-center" href="https://angular.io/tutorial">Tour of Heroes</a>
 </li>
 <li class="navbar-link"><a class="text-center" href="https://github.com/angular/angular-cli/wiki">CLI Documentation</a>
 </li>
 <li class="navbar-link"><a class="text-center" href="https://blog.angular.io/">Angular Blog</a>
 </li>
 </ul>
 </div>
 </nav>
 </div>
 </div>
 </div>
</div>

The outer div allows us to uniformly apply our color across the length of the page. The next div will give us the margin for the content. The next important piece is the nav node.

  • The nav tag: defines the where the navigation information lives. This tells the code how to build the navbar
    • class=”navbar navbar-expand-md navbar-blue”: navbar-expand-md: tells bootstrap at what point to collapse and expand the navbar
  • Button node
    • When the navbar is collapsed we want to a button icon to display
    • class attribute
      • navbar-toggler: tells the application this is what toggles the menu
      • ml-auto: auto margin this automatically pushes the div to the left (short for: margin-left: auto)
      • Custom-toggler is a custom icon defined in the component’s style
    • data-toggle: This tells you how you want data toggle to start on page load. In this call, we will use collapse. The options are
      • .collapsehides content
      • .collapsingis applied during transitions
      • .collapse.showshows content
    • Ng-bootstrap needs to know when to extend the menu (if collapsed). We will add a boolean on the component to track this. The button click will manage the boolean
  • Menu/Navbar items:
    • The wrapper div will start collapsed as indicated on the class with “collapse navbar-collapse”
    • We also tell ng bootstrap where the menu items are located, so that they can be displayed in the menu dropdown. This is down with theid=”navbarSupportedContent”
    • [ngbCollapse] binds the boolean to ngbootstrap component. This controls when to expand and collapse the menu
    • List
      • Using a list we defined the menu items
      • class
        • Navbar-nav tell bootstrap these are the navigation items
        • ml-auto

navbar.component.ts

The only thing we add here is ‘isCollapsed: boolean = true;’ to the class. This is how we will track if the navbar menu is open or closed.

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

@Component({
 selector: 'app-navbar',
 templateUrl: './navbar.component.html',
 styleUrls: ['./navbar.component.scss']
})

export class NavbarComponent implements OnInit {
 isCollapsed: boolean = true;
 constructor() { }
 ngOnInit() {
 }
}

navbar.component.scss

A few styles have been added to prettify the navbar and ensure the layout, but we will not go over them here. Please take a look at the source code in the resources link below to see all the styles that where added. The only real style of note is the .custom-toggler

The .custom-toggler is the 3 horizontal bars used as a menu expand button. In this case, we want the bars to be white. Notice the stroke=’rgba(255,255,255,1)’ portion. Modifying this will allow us to change the color of the bars.

.custom-toggler .navbar-toggler-icon {
 background-image: url("data:image/svg+xml;charset=utf8,%3Csvg viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath stroke='rgba(255,255,255, 1)' stroke-width='2' stroke-linecap='round' stroke-miterlimit='10' d='M4 8h24M4 16h24M4 24h24'/%3E%3C/svg%3E");
}

Testing

Now that the coding is done let’s run our application. On the command, in our project folder run ng serve. This will tell angular cli to compile the code and start hosting the page a localhost:4200. If we now open a web browser and navigate to http://localhost:4200 we will see our navbar. If your browser is the width of the computer screen you will see something like the image to the right.

By resizing the browser to have a smaller width we will see the menu items on the right be replaced with the toggle icon.

Now if we click the toggle icon we will get the menu dropdown.

Conclusion

Creating a responsive navbar using Angular 5 and Bootstrap 4 is a simple and effective way to significantly improve user experience. With this template you can easily change the color, logo, navigation menu items. Please experiment and tell us how you’ve customized your navbar. Be sure to visit the source at https://github.com/djchi82/angular-bs-scalable-navbar.

Resources

Categories: Blog

Tags: , , , ,

Ryan Van Fleet
01 Aug, 2018