Angular Routing

  • Angular Routing is used for routing i.e navigate from one page to another.
  • Links which direct to a new link or new page.
  • Routing module is added as default during project setup.
  • App-routing.module.ts is created during initial project creation.
App-routing.module.ts

You can check in app.module.ts file, where app-routing is imported during project setup.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [];

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

Const routes will hold all our routes needed in this project. We need to add directive in app.component.html to make this routing functional.

<router-outlet></router-outlet>

App.component.html
<div class="toolbar" role="banner">
	<span>Welcome to {{ title }}</span>
</div>
<div class="content">
  <router-outlet></router-outlet>
</div>

Lets create two components and navigate between them using our angular routes.

ng g c home
Below screenshot shows the output of this command

myfirstapp-component

We can see the component files for home components are generated and app.module.ts is updated.

ng g c contact
Below screenshot shows the output of this command

contact-component

We can see the component files for contact components are generated and app.module.ts is updated.

Now lets define the routes in app-route.module.ts as below


import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component'; 
import { ContactComponent } from './contact/contact.component';

const routes: Routes = [
  {path:"home", component:HomeComponent}, 
  {path:"contact", component:ContactComponent} 
];

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

As we can see, home and contact components are imported and routes are defined and mapped to components. So whenever there is a request for /home it will navigate to home component and /contact will navigate to contact component.

Let add home and contact menu in app.component.html as below.


<div class="toolbar" role="banner">
   <span>Welcome to {{ title }}</span>
 </div>
<div class="content">
  <nav>
    <a routerLink = "/home">Home </a> | 
    <a routerLink = "/contactus">Contact Us  </a>
 </nav>
  <router-outlet>
Below screenshot shows the output on the browser.

contact-component-output

When we click on home, we navigate to home component and content in home.component.html is displayed.

Below content is from home.component.html

 <p>home works! </p>

Below content is from contact.component.html

 <p>contact works! </p>
  
Below screenshot shows the output on the browser when we click home

home-component-output

Below screenshot shows the output on the browser when we click contact.

contact-component-output

Subscribe Now