One of every web application’s main features is navigation, and to enable it in our project, we need to use routing. The Angular Router enables navigation from one view to the next as users perform application tasks.

In our navigation menu, we are going to have three menu options: one for the home screen, another one for the owner operations, and the last one for the account operations. Hopefully, this will help you realize the advantages of using multiple modules inside a project and how the lazy content loading helps your application perform better.

If you want to see all the basic instructions and complete navigation for the .NET Core series, check out the following link: Introduction of the .NET Core series.

For the complete navigation and all the basic instructions of the Angular series, check out: Introduction of the Angular series.

The source code is available at GitHub .NET Core, Angular, and MySQL. Part 8 – Source Code

This post is divided into several sections:

Creating a Navigation Menu

So, let’s start with the Angular CLI command : ng g component menu --skipTests

We are going to use Bootstrap classes to implement the navigation menu within the menu.component.html file:

<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
    <a class="navbar-brand" href="#">Account-Owner Home</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" 
    aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
  
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav mr-auto">
        <li class="nav-item">
          <a class="nav-link" href="#">Owner Actions </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Account Actions </a>
        </li>
      </ul>
    </div>
</nav>

This is how the menu.component.ts file should look like:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html',
  styleUrls: ['./menu.component.css']
})
export class MenuComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }
}

And we are going to change our app.component.html file:
<div class="container">
  <div class="row">
      <div class="col">
        <app-menu></app-menu>
      </div>
  </div>
</div>

Start your angular project by typing ng serve and navigate tohttp://localhost:4200. You should be able to see our menu on the screen:

Menu Angular routing

Configuring Angular Routing

The page with the welcome message is not available anymore because we have changed the app.component.html file. To enable navigation between all the pages inside this project, we need to configure the Angular routing.

Let’s open the app.module.ts file and modify it:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router'

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { MenuComponent } from './menu/menu.component';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    MenuComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot([
      { path: 'home', component: HomeComponent },
      { path: '', redirectTo: '/home', pathMatch: 'full' }
    ])
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

In this file, we may notice a MenuComponent inside declarations array. It was imported earlier during the creation of the navigation component. Also, check out the RouterModule, which is the module for the Angular routing. We are going to use RouterModule.forRoot to define routes for our application.

When we create more than one module inside the application, we can use the forRoot() function provided by the RouterModule, only in the main(root) module. In this project, it is the app.module file. In all other modules, we must use the forChild() function. The forRoot() function accepts an array of objects as a parameter. Every element of that array consists of the path and the target component for that path. So, the path: ‘home’ means that on the address http://localhost:4200/home we are going to serve the HomeComponent. The other line inside the forRoot function is the default redirection to the home page.

Note that the best practice for large projects is to keep router array in the separate file, but for the sake of the simplicity of this example, we are keeping it inside the forRoot function. If you still want to create a separate routing module, you can learn more about it here: Angular Material Navigation and Routing.

To show the home page, modify app.component.html:

<div class="container">
  <div class="row">
      <div class="col">
        <app-menu></app-menu>
      </div>
  </div>
  <div class="row">
    <div class="col">
      <router-outlet></router-outlet>
    </div>
  </div>
</div>

The router-outlet is a container for the routing content. So basically, all the content that exists on the address you are routing to is going to be presented inside that container.

Now if you navigate to the localhost:4200 you should be able to see the following result:

Home page Angular routing

Styling links

If you want to style your active link in the menu, change your <a> tag:

<a class="navbar-brand" [routerLink]="['/home']" routerLinkActive="active" 
                [routerLinkActiveOptions]="{exact: true}">Account-Owner Home</a>

With the routerLinkActive, we are setting up the CSS class name we want to use to style the active link. Furthermore, the routerLinkActiveOptions is going to allow us to add a class only if there is an exact match of the link and the URL.

Now in the menu.component.css file, we are going to add the .active class:

.active{
    font-weight: bold;
    font-style: italic;
    color: #fff;
}

Excellent. If we inspect our application, we are going to see that the Account-Owner Home link is now white and bold.

Creating the Not-Found Component

We have working navigation.

To complete the Angular routing part of this post, we are going to create a component with the name not-found. The application is going to redirect a user to this component when he types a none existing route in the URL.

To do that, let’s execute the familiar command:

ng g component error-pages/not-found --skipTests

This is the folder structure:

not-found folder structure Angular routing

Let’s modify the not-found.component.ts file:

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

@Component({
  selector: 'app-not-found',
  templateUrl: './not-found.component.html',
  styleUrls: ['./not-found.component.css']
})
export class NotFoundComponent implements OnInit {

  public notFoundText: string = `404 SORRY COULDN'T FIND IT!!!`

  constructor() { }

  ngOnInit() {
  }
}

Pay attention to the string value of the variable notFoundText. We are not using apostrophes but backticks (`). All the content inside the backticks will be considered as a string, even the apostrophe sign in the string.

Modify the not-found.component.html file:

<p>
  {{notFoundText}}
</p>

Modify not-found.component.css file:
p{
    font-weight: bold;
    font-size: 50px;
    text-align: center;
    color: #f10b0b;
}

Finally, modify the forRoot function in the app.module.ts file:
imports: [
    BrowserModule,
    RouterModule.forRoot([
      { path: 'home', component: HomeComponent },
      { path: '404', component : NotFoundComponent},
      { path: '', redirectTo: '/home', pathMatch: 'full' },
      { path: '**', redirectTo: '/404', pathMatch: 'full'}
    ])
  ],

You may notice two changes. With the first change, we are declaring the path 404 and assigning the component NotFoundComponent to that path. Now our component is going to be visible on the localhost:4200/404. The second change means that whenever you search for any route that doesn’t match any of our defined routes, the application redirects you to the 404 page.

Typing localhost:4200/whatever should return the following result:

not-found page Angular component

Conclusion

As you might have noticed, creating the menu and using the routing in the angular project is pretty straightforward. Although we are not creating a large project, it is quite big enough to demonstrate the usage, configuration, and routing of all the pages we currently have. Of course, we are going to create routes for all new pages that we introduce to our project.

By reading this post you’ve learned:

  • How to create a navigation menu
  • How to create and configure the routing
  • The way to style the route links

Thank you for reading the post, hopefully, it was helpful to you.

In the next part of the series, we are going to show you how to fetch the data and consume the API with the HTTP and Observables.