angular routing step by step tutorial devmedium

Enable Routing in Angular Step By Step

9 min read

Hello guys, Routing and Navigation is one of the most important feature of web. With help of navigation links user visit different parts of your web application or website. In this post i will demonstrate how you can enable Routing in your Angular Project with very simple steps using Angular CLI and also manually.

At the end of this post you will find the answers to the following questions.

  • How to create AngularRoutingModule.
  • How to redirect on different routes using the HTML anchor tag?
  • Why use router-outlet ?
  • How to set a default route ?
  • What are wildcard routes ?

If you are using Angular CLI to create a angular project so it will ask if you want to add Angular Routing in your project.

Would you like to add Angular routing? (y/N)

By pressing ‘y’ CLI will do some basic configuration of routing module in the project. But for enable Routing manually we have to follow some steps.

Before start routing, we should have at least two components in our app so we can navigate from one component to another.

Step 1) Create Home and About Us component using CLI

ng g c home 
ng g c aboutus

Step 2) Create a file app-routing.module.ts inside src/app/

In this file import NgModule from @angular/core and Routes, RouterModule from @angular/router as shown below.

Create a routes array of type Routes. In the next step we will pass the objects of path in this array.

app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
 
const routes: Routes = [];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Step 3) Import the components in app-routing.module.ts which you want to navigate and update the routes array.

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'aboutus', component: AboutusComponent },
 ];

Explanation: There are two important keys in each object of routes array first is path and second is component. Path denotes the segment of the URL on which the user redirects to the specific component. So when we hit the URL http://localhost:4200/home HomeComponent will be open.

In the above example 2 route objects have been added. That will redirect users to the specific components.

Step 4) Import AppRoutingModule inside imports array of root module i.e app.module.ts

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
 
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { AboutusComponent } from './aboutus/aboutus.component';
 
@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    AboutusComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 5) Replace all code of app.component.html with below code.

<ul>
  <li><a routerLink="/home">Home</a></li>
  <li><a routerLink="/aboutus">About us</a></li>
</ul>
<router-outlet></router-outlet>

Why use router-outlet ?

Router-Outlet used to load the different components dynamically. The content of the activated component loads inside the router-outlet.

Step 6) Serve the app using ng serve and hit http://localhost:4200/

You will see the default screen with two links Home and About Us. Click on the “Home” link and you will redirect to the HomeComponent.

Now what ,If we want the home component as a default screen so when user hit the URL http://localhost:4200 home component should be open.

To achieve this add one more object in the routes array. If user will not specify anything in the URL this will redirect the user to the home route.

{ path: '', redirectTo: '/home', pathMatch: 'full' }

Wildcard Routes

Test your application by hitting this URL http://localhost:4200/xyz. This will redirect you to the home component because the route “xyz” does not exist.

If a user is trying to navigate a part of our application that does not exist. We should display a page containing a message “Page Not Found”.

Generate a page not found component.

ng g c page-not-found

Adding a wildcard route

Add this object in the last of routes array.

 
{ path: '**', component: PageNotFoundComponent }

A Route with the path “**” is known as a wildcard route. Router sends the user to the PageNotFoundComponent if any other route does not match.

So our final app-routing.module.ts file will look like.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutusComponent } from './aboutus/aboutus.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
 
 
const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'aboutus', component: AboutusComponent },
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: '**', component: PageNotFoundComponent }
];
 
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

And app.module.ts file will be like.

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { AboutusComponent } from './aboutus/aboutus.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    AboutusComponent,
    PageNotFoundComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Check the complete code in github

Thanks for reading this post. Please upvote this post if you like it and also share it with your friends who are learning angular.