Routing and Navigation In Angular step by step

Introduction

In this article, we’ll understand how routing works in Angular. we examine how to configure routes and tie routes to actions, and we define routes to navigate between multiple views in our application. so, our sample applications often provide many sets of data, in multiple layouts, across multiple views. the Routing provides a way for the user to navigate between those many views of the application.

In our application, we will create the Vehicles list component as a nested component. We instead want to define a set of routes. so, the user can navigate to the Welcome view, Vehicle List view or Vehicle Detail view.

Using Angular CLI

Let’s build the vehicle detail component. So let’s just create a shell for the Vehicle detail component so we can route to it.

We could use the Explorer and create new component class and template files manually, or we could use the Angular CLI to automatically create those files.

Let’s go and open a terminal window. we’ll use the integrated terminal built into VS Code. If you don’t already have the CLI installed, install it now using NPM command.

 > npn install -g @angular/cli

After that, we type ng for the Angular CLI, g for generating, c for the component, and the name of our component. we want to create this component under the Vehicles folder, we add the path to the desired component name.

 > ng g c vehicle/vehicle-detail --flat

owever, Angular will create a new folder for this component. we want the contents of our Vehicle folder to be flat. We’ll use the –flat option to achieve this.

CREATE src/app/vehicles/vehicle-detail.component.html
CREATE src/app/vehicles/vehicle-detail.component.spec.ts
CREATE src/app/vehicles/vehicle-detail.component.ts
CREATE src/app/vehicles/vehicle-detail.component.css
UPDATE src/app/app.module.ts

You can see here, it created the style sheet and the CSS file, the template in an HTML file, and the class in a TypeScript file. here, our generated template

//vehicle-detail.component.html

<div class='card'>
	<div class='card-header'>
	 {{vehicleName + ': '+ vehicle?.vehicleName}}
	</div>
</div>

We use interpolation to bind to a vehicle name. the Vehicle property is undefined, so we would get a runtime error telling us it can’t read the property Vehicle name of undefined. so, There are several common ways to prevent undefined property errors.

We could use the safe navigation operator defined with a question mark. The safe navigation operator guards against null and undefined values when navigating an object’s properties. If the Vehicle object is null or undefined. the safe navigation operator simply returns null and does not attempt to access the VehicleName property. hence, we don’t see an undefined property error.

After that, let’s open the TypeScript file. The generated component class has all of the basic syntaxes in place. All it needs is the page title and Vehicle properties that we are referencing in the template. Notice that the CLI generated the selector property here.

//vehicle-detail.component.ts

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

@Component({
	selector: 'pm-vehicle-detail',
	templateUrl: './vehicle-detail.component.html',
	styleUrls:['./vehicle-detail.component.css']
})
export class VehicleDetailComponent implement OnInit {
	vehicleName: string = 'Vehicle Details';
	vehicle: IVehicle;

	constructor() { }
	
	ngOnInit()
	{
	}
}

The selector property is only required if the component will be nested within another component. We won’t need to nest this component, we’ll instead display the component’s view as part of the routing,

So, Now let’s import our new component in the Angular module. Every time we add a component to the application, we need to declare the component in an Angular module.

Angular module

We have Angular module, AppModule, so the Vehicle detail component and the welcome component must be added to the declarations array for the AppModule.

 //app.module.ts
 
 import { BrowseModeule } from '@angular/platform-browser';
 import { NgModule } from '@angular/core';
 import { FormsModule } from '@angular/forms';
 import { HttpClientModule } from '@angular/common/http';
 
 import { AppComponent } from '@angular/component';
 import { VehicleListComponent } from './Vehicle/Vehicle-list.component';
 import { ConvertToSpacePipe } from './shared/convert-to-spaces.pipe';
 import { StarComponent } from './shared/star.component';
 import { VehicleDetailComponent } from './Vehicle/Vehicle-list.component';
 
 @NgModule({
    declarations: [
	  AppComponent,
	  VehicleListComponent,
	  ConvertToSpacePipe,
	  StarComponent,
	  VehicleDetailComponent
	],
	imports: [
	  BrowseModeule,
	  FormsModule,
	  HttpClientModule
	],
	bootstrap: [AppComponent]
 })
 export class AppModule{}

Now, we are ready to add routing to our application.

How Routing Works?

An Angular application is a single-page application. That means all of our views are displayed within one page, normally defined in the index.html file.

//index.html

<!doctype html>
<html lang=*en>
<head>
  <meta charset="utf-8">
  <title>Application</title>
  <base href="/">
  <meta rel="icon" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<pm-root><pm-root>
</body>
</html>

The first step to set up routing is to define a base element in the head tag of the index.html file. So, the Angular CLI already did that for us. This element tells the router how to compose the navigation URLs. and manage which view to display when? That’s the purpose of routing. We configure a route for each component that wants to display its view on the page.

As part of our application design, we provide a menu, a toolbar, buttons, images or data links that allow the user to select the view to display. We tie a route to each option or action. When the user selects the option or performs the action, the associated route is activated. Activating a component’s route displays that component’s view.

for example,

 <a routerLink="/vehicles">Vehicle List</a>
 
 { path:'vehicles', component: VehicleListComponent }
//vehicle-list.component.ts
 import { Component } from '@angular/core';
 
 @Component({
   templateUrl: './vehicle-list.component.html' 
 })
 export class VehicleListComponent { }

Configuring Routes

Routing is component-based, so, we identify the set of components. that we want to provide as routing targets and define a route for each one. Let’s go and understand how it works. An Angular application has one router manage by Angular’s router service. and we know that before we can use the service we need to register the service provider in an Angular module.

 //app.module.ts
 ....
 import { RouterModule } from '@angular/router';
 
 @NgModule({
    imports: [
	  BrowseModeule,
	  FormsModule,
	  HttpClientModule,
	  RouterModule
	],
	declarations:[ ..],
	bootstrap: [AppComponent]
 })
 export class AppModule{}

So, here Angular provides a RouterModule in the angular/router package that registers the router service provider. To include the features of this external module in our application. we need to add it to the imports array of our application’s Angular module.

Also to register the service provider. the RouterModule also declares the two router directives, routerLink, and router-outlet. By importing the RouterModule, our component templates can use these or any other router directives. RouterModule also exposes the routes we configure.

Before we can navigate to a route, we need to ensure that the routes are available to the application. We do this by passing the routes to RouterModule, like this. We call the RouterModule forRoot method and pass our array of routes to that method.

RouterModule.forRoot([])

The router must configure with a list of route definitions. Each definition specifies a route object. Each route requires a path. The path property defines the URL path segment for the route.

For that, we go to our Angular module, add the appropriate import statement, then add RouterModule to the imports array. This registers the router service provider, declares the router directives, and exposes the configured routes. How does the RouterModule know about our configured routes? We pass them into the RouterModule by calling the forRoot method. We then configure the routes here by passing them in using an array. Let’s start with the Vehicle routes. For each route, we specify the path and a reference to the component.

 //app.module.ts
 
 import { BrowseModeule } from '@angular/platform-browser';
 import { NgModule } from '@angular/core';
 import { FormsModule } from '@angular/forms';
 import { HttpClientModule } from '@angular/common/http';
 
 import { AppComponent } from '@angular/component';
 import { VehicleListComponent } from './Vehicle/Vehicle-list.component';
 import { ConvertToSpacePipe } from './shared/convert-to-spaces.pipe';
 import { StarComponent } from './shared/star.component';
 import { VehicleDetailComponent } from './Vehicle/Vehicle-list.component';
 
 @NgModule({
    declarations: [
	  AppComponent,
	  VehicleListComponent,
	  ConvertToSpacePipe,
	  StarComponent,
	  VehicleDetailComponent
	],
	imports: [
	  BrowseModeule,
	  FormsModule,
	  HttpClientModule,
	   RouterModule.forRoot([
	   { path:'vehicles', component: VehicleListComponent},
	     path: 'vehicles/:id',component:VehicleDetailComponent},
		 path: 'welcome' , component:WelcomeComponent},
		 path: '',redirectTo:'welcome',pathMatch: 'full'},
	   ]),
	],
	bootstrap: [AppComponent]
 })
 export class AppModule{}

When this route is activated, this URL path segment is appended to the URL of our application. The user can type in or bookmark the resulting URL to return directly to the associated component’s view.

Thanks for Reading Article! I hope this get’s you started app using Angular. Take care.

Leave a Reply

Your email address will not be published. Required fields are marked *