Skip to content
  • iImagine
  • Register
  • Log In

Web Development School

Learning made easy.

  • Books
    • Beginning Web Development with ASP.Net Core & Client-Side Technologies
      • TOC
      • Part 1
        • Chapter 1: Static HTML – Designing the landing page
      • Part 2
        • Chapter 2: ASP.Net Core – Let’s talk Dynamic
        • Chapter 3: Introduction to ASP.Net Core MVC
          [ASP.Net Core v9]
      • Part 4
        • Chapter 7: Using Server Side & Client Side technologies together
          [ASP.Net Core v7 & Angular 15]
  • Environment Setup
    • Installing Angular
    • Installing Visual Studio 2022
    • Installing SQL Server 2022 Express
    • Installing Postman
    • Installing Git for Windows
  • Blog
  • iImagine WebSolutions
  • Events
  • Learning Videos
  • Toggle search form

Routing and Navigation

In the last module we learned how to load up the Vehicles component into the root component (AppComponent). But what if we have multiple components? And we most certainly will. How do we navigate between them?

In this module we are going to create a second component. We will create a Welcome Component and build the required routing infrastructure to navigate between the Welcome screen and the Vehicle results.

Note: At this point I am copying the project from the Module10 folder to a Module11 folder. The pathway I am using for development here is:
C:\Development\FredsCars\FullStack\Module11.
Table Of Contents
  1. Create the Welcome Component
  2. Create a Feature Module
    • Create the Routing Module (AppRoutingModule)
  3. Register a Feature Module
  4. The router-outlet element
  5. Navigation
    • Create the Navigation Component
    • Using the -module switch
  6. Add a welcome message
  7. What's Next

Create the Welcome Component

Open up a PowerShell or command prompt and navigate to the FredsCars Angular project and run the following command.

ng generate component Welcome --skip-tests

If you look in Solution Explorer you should have a new Welcome component living its own directory.

Create a Feature Module

If you recall from module 8, “WeatherForecast: Understanding the basics”, this is the basic definition of an Angular Module.

An Angular Module is a place where pieces of code be it components, directives, services or even other modules can be grouped together in order to provide some form of functionality that can be reused in many places throughout the application.

Up until now we’ve only had one Angular Module in our application, AppModule (the root module). It’s time to write our first custom module, or feature module.

Create the Routing Module (AppRoutingModule)

In Solution Explorer, right click on FredsCars/src/app and select “Add –> New Item”.

Name the file app-routing.module.ts and fill it with the following code.

import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { VehiclesComponent } from "./vehicles/vehicles.component";
import { WelcomeComponent } from "./welcome/welcome.component";

const routes: Routes = [
  { path: '', component: WelcomeComponent, pathMatch: 'full' },
  { path: 'vehicles', component: VehiclesComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

In the code above we create a constant variable called routes of type Routes which is used to hold a Route Array. This will represent a Route configuration for the Router Service which is contained in RouterModule. We import both Routes and RouterModule from @angular/router package at the top of the TypeScript file.

Within the Route Array we define two routes. The first route will load the new Welcome component as the default component when no path is specified after the hostname and optional port number or if there is a ‘/’ character at the end of the hostname and optional port number.

{ path: '', component: WelcomeComponent, pathMatch: 'full' }

The above path can be reached by

https://localhost:4200

or

https://localhost:4200/

The second route will load the Vehicles component when the specified path after the hostname and optional port number is ‘/vehciles’.

{ path: 'vehicles', component: VehiclesComponent }

The above path can be reached by

https://localhost:4200/vehicles

Next the AppRoutingModule class is marked with the NgModule decorator. The NgModule imports section imports the RouterModule Service and passes to it the routes configuration we specified. The NgModule exports section exports the RouterService and makes it available to the rest of the application (once we register AppRoutingModule in the AppModule (the root module).

Register a Feature Module

Next we need to register AppRoutingModule in AppModule (the root module).

Open “FredsCars/src/app/app.module.ts” and make the modifications shown below in bold blue font.

import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';
import { VehiclesComponent } from './vehicles/vehicles.component';
import { WelcomeComponent } from './welcome/welcome.component';

@NgModule({
  declarations: [
    AppComponent,
    VehiclesComponent,
    WelcomeComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

In the code above we simply added our new feature module (AppRoutingModule) to the NgModule imports section of the root module (AppModule). Since we imported and configured the Angular Routing service in AppRoutingModule and then registered it in the root module, our defined routes should be available throughout the application (assuming we import RouterModule where ever we want to use it).

The router-outlet element

Currently the root component (AppComponent) has the following html.

<app-vehicles></app-vehicles>

So when the application starts up that’s it. The Vehicles component is loaded up and there is no way to see any other page, screen, or component.

Angular uses the <router-outlet> element to load the appropriate component with the path configuration that matches the current browser URL.

There is no better place to put this element then the root component (AppComponent) since it is the first component loaded up and bootstrapped by the root module (AppModule). So let’s put it in there!

Open FredsCars/src/app/app.component.html and fill it with the modified code shown below.

<div class="container">
  <router-outlet></router-outlet>
</div>

Now our root component has the <router-outlet> element to house the appropriate component for the current browser URL.

If you run the application at this point, you should see the following results.

It looks like our routing configuration is working.

The URL in the browser is: https://localhost:4200.

And the Welcome component is loaded as specified in AppRoutingModule with the following path:

{ path: '', component: WelcomeComponent, pathMatch: 'full' }

I think we are well on our way. But the user still has no way to get to the Vehicle results screen. We need to provide some kind of UI to navigate between routes. And that’s what we will do next.

Navigation

The last piece of the puzzle here is to create the Navigation UI. And just like the Welcome screen, or Vehicles screen, we can provide this in a component. As we are starting to see, Components are really the building blocks of an Angular application.

Create the Navigation Component

Open a command window and navigate to the FredsCars Angular folder.

Run the following command as a dry run just to make sure it is going to do what we think it will.

ng generate component NavMenu --skip-tests --dry-run

You should see the following results in the command window.

It looks like the command will do what we want; Create the three expected component files and register the component in the root module. Let’s run it for real this time. Run the following command.

ng generate component NavMenu --skip-tests

In Solution Explorer you should now have a new FredsCars/src/app/nav-menu directory with the three component files in it.

Using the -module switch

When we ran the --dry-run switch we confirmed that app.module.ts would be updated and can assume the update was to register the new NavMenu component in the root module, AppModule.

Now that we have two Angular Modules, AppModule and AppRoutingModule, Angular may not always know which module you want the ng generate component command to register the new component in.

This is why it always a good idea to do a dry run for CLI commands before you actually execute them. However if you just want to explicitly tell Angular which module to register the new component in, you can use the --module switch to specify like this:

ng generate component NavMenu --module=app --skip-tests

Open nav-menu.component.html from the new directory and modify the code as shown below.

<header>
  <nav>
    <a [routerLink]="['/']">Home</a>
    |
    <a [routerLink]="['/vehicles']">Vehicles</a>
  </nav>
</header>

In the html above, we define two anchor elements. They each use an Angular routerLink directive to create an href attribute which will point to one of our two route configuration paths.

Open the nav-menu.component.ts file and look at it’s code.

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

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

Notice the NavMenu Component’s Component selector property value. It is app-nav-menu. So, we need to place an <app-nav-menu> element somewhere in the application html for the component to load up. Where should we do this?

If we place the <app-nav-menu> element directly above the <router-outlet> element in the root component, our front-end Angular application will truly behave like an SPA (Single Page Application). The only contents the root component will have is the Navigation UI and the <router-outlet> element reflecting the appropriate component for the current browser URL.

Let’s go back to app.component.html one more time and make the code modification shown below.

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

Now if you run the application in debug mode, you should see the following results; Our new Navigation UI component on top, and the default Welcome component under it.

In the browser click the Vehicles link and you should see the vehicle results from the Vehicle component reflected in the URL.

Add a welcome message

Before we wrap up this module, let’s fix one last little thing. Let’s put a more appropriate message on our Welcome screen rather then the autogenerated, “It works!” message.

Open FredsCars/src/app/welcome/welcome.component.html and fill it with the code below.

<h1>Welcome to Fred's Cars!</h1>
Where you'll always find the right car, truck, or jeep.
Thank you for visiting our site.

And now the welcome screen should look like the results below.

What’s Next

In this module we got our routing infrastructure into place and we can now navigate to different parts of the application. In the next module we will turn to dressing up the appearance a bit and learn a new way to apply styling and design to our application using a component library.

< Prev
Next >

Leave a ReplyCancel reply

Chapter 1: Static HTML – Designing the landing page.

  • Static HTML – Designing the landing page.
  • Let’s get started!
  • Mock your site with HTML
  • Make CSS easy with Bootstrap
  • Mock your content
  • Introducing JavaScript
  • JavaScript Code Improvements
  • Results Data
  • Images and the HTML Image Element.
  • Revisiting Reusability for CSS and JavaScript
  • Reuse for HTML: PART 1
  • Reuse for HTML: PART 2
  • Details Page – Using a Bootstrap Component
  • Creating Links
  • Chapter One Conclusion

Chapter 2: ASP.Net Core – Let’s talk Dynamic

  • Introduction to ASP.Net Core
  • What is .Net?
  • What is ASP.Net
  • Introduction to Entity Framework Core

Chapter 3: ASP.Net MVC Core – Models, Views, and Controllers [ASP.Net Core v9]

  • Introduction to ASP.Net Core MVC
  • Create the project: ASP.Net Core MVC
  • Explore the ASP.Net Core Empty Web Project Template
  • Configure the Application for MVC
  • Create a Controller: Home Controller
  • Create a View: Index View for the Home Controller
  • Install Bootstrap using Libman
  • Create the Layout template
  • Create the Model
  • Install EF Core & Create the Database
  • Seed the Database: Loading test data
  • DI (Dependency Injection): Display a List of Vehicles
  • Repository Pattern: The Vehicles Repo
  • Unit Test 1: Home Controller Can Use Vehicle Repository
  • Unit Test 2: Vehicle Repository Can Return List
  • Add the ImagePath Migration and Thumbnail images to results
  • Pagination: Create a Custom Tag Helper
  • Sorting
  • Category Filter
  • Partial View: Break out the vehicle results
  • View Component: Create dynamic category buttons
  • Create the Details page
  • Create the Create Page

Chapter 7: Using Server Side & Client Side technologies together. [ASP.Net Core v7 & Angular v15]

  • Intro to Full Stack Development
  • Fred’s Cars – Full Stack Development
  • Prepare the environment
  • Create the Visual Studio Solution
  • Add the ASP.Net Core Web API project
  • Add the Angular Project
  • Wire it up!
  • WeatherForecast: Understanding the basics
  • Vehicles API Controller: Mock Data
  • Vehicles Angular Component: Consuming Data
  • Routing and Navigation
  • Using a Component Library: Angular Material
  • Our first Angular Material Component: MatToolbar
  • Configuring for Saas: CSS with superpowers
  • Create the Header & Footer components
  • Displaying Results with MatTable
  • Loading: Using a Progress Spinner
  • MatTable: Client-Side Paging and Sorting
  • MatSidenav: Create a Search Sidebar
  • MatCheckbox: Category Search UI
  • Adding an image to the welcome page
  • Create the database with Entity Framework Core migrations
  • MatPaginator & PageEvent: Custom Server-Side Paging
  • Unit Testing: Custom Server-Side Paging
  • Repository Pattern: VehicleRepository
  • Unit Test: Paging in the Vehicles controller
  • Server-Side Sorting
  • Unit Tests: Sorting
  • Filter (Quick Search)
  • Unit Tests: Filter feature
  • Advanced Search: Categories
  • Unit Tests: Search by category
  • Progress Spinner: Final Fix

TOC

  • What were WebForms?
  • Enter MVC
    • Understanding MVC
    • Advantages of MVC
  • ASP.Net Core MVC – A total rewrite
  • ASP.Net Core 2 MVC – Here come Razor Pages
    • Understanding Razor Pages
  • ASP.Net Core 3 – Dropping the MVC reference
    • Understanding Blazor
  • Dropping the MVC reference
  • Hello .Net 5!
  • What’s Next? – Here comes .Net 6.

Recent Posts

  • Angular Commands Cheat Sheet
  • Installing Git for Windows
  • Installing Postman
  • Installing SQL Server 2022 Express
  • Installing Visual Studio 2022

Recent Comments

No comments to show.

Archives

  • November 2023
  • October 2023
  • June 2023
  • October 2021

Categories

  • Angular
  • ASP.Net
  • Environment Setup
  • See All
  • SQL Server
  • Visual Studio
  • Web API & Rest Services

WordPress Theme Editor

Copyright © 2025 Web Development School.

Powered by PressBook Blog WordPress theme