Routing Explained

Angular Routing

Routing is used to move from one page to another page in an Angular application.

A single-page application cannot work on one page only, so routing is required.

Routing converts Angular components into pages.


Creating Pages Using Components

Pages are created using Angular components.

All page components are kept inside a pages folder.

Example components created:

  1. Home
  2. About
  3. Login
  4. Profile

Registering Routes (app.routes.ts)

Components must be registered in the routing file to work as pages.

Each route contains a path and a component.

import { Routes } from '@angular/router';
import { HomeComponent } from './pages/home/home.component';
import { AboutComponent } from './pages/about/about.component';
import { LoginComponent } from './pages/login/login.component';
import { ProfileComponent } from './pages/profile/profile.component';

export const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'login', component: LoginComponent },
{ path: 'profile', component: ProfileComponent }
];

The empty path ('') is the default route and loads the Home page.

Router Outlet

router-outlet is required to display pages on the UI.

Without it, routing will not work.

<router-outlet></router-outlet>

Pages are shown exactly where router-outlet is placed.


Creating Page Content (Example)

Each page component contains simple content.

<h1>Home Page</h1>


<h1>About Page</h1>


<h1>Login Page</h1>


<h1>Profile Page</h1>


Navigation Using Router Link

routerLink is used instead of href.

It changes pages without reloading the application.

<ul>
<li><a routerLink="/">Home</a></li>
<li><a routerLink="/login">Login</a></li>
<li><a routerLink="/about">About</a></li>
<li><a routerLink="/profile">Profile</a></li>
</ul>

<hr>
<router-outlet></router-outlet>

Why Not Use href

Using href reloads the page.

routerLink changes pages without reload, so it is preferred in Angular.