0
0
Angularframework~5 mins

Why routing is needed for SPAs in Angular

Choose your learning style9 modes available
Introduction

Routing helps single-page apps show different pages without reloading the whole site. It makes the app feel fast and smooth like a real website.

You want users to move between different views or pages in your app without waiting for full reloads.
You need to keep the app state while switching content, like a shopping cart or user profile.
You want to share links that open specific parts of your app directly.
You want to improve user experience by loading only needed parts of the app on demand.
Syntax
Angular
const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: '', redirectTo: 'home', pathMatch: 'full' }
];

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

Routes define which component shows for each URL path.

RouterModule.forRoot sets up routing for the whole app.

Examples
Simple routes for dashboard and profile pages.
Angular
const routes: Routes = [
  { path: 'dashboard', component: DashboardComponent },
  { path: 'profile', component: ProfileComponent }
];
Redirect empty path to dashboard and catch all unknown paths.
Angular
const routes: Routes = [
  { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
  { path: '**', component: PageNotFoundComponent }
];
Sample Program

This example shows routing setup with two pages: Home and About. The app starts at Home. Clicking links changes the URL and shows the right page without reloading.

Angular
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home.component';
import { AboutComponent } from './about.component';

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: '', redirectTo: 'home', pathMatch: 'full' }
];

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

// HomeComponent
import { Component } from '@angular/core';
@Component({
  selector: 'app-home',
  template: `<h1>Home Page</h1><p>Welcome to the home page!</p>`
})
export class HomeComponent { }

// AboutComponent
import { Component } from '@angular/core';
@Component({
  selector: 'app-about',
  template: `<h1>About Page</h1><p>Learn more about us here.</p>`
})
export class AboutComponent { }
OutputSuccess
Important Notes

Routing keeps your app fast by not reloading the whole page.

Use routerLink in templates to create clickable links that change views.

Always define a default route to avoid blank pages.

Summary

Routing lets SPAs show different pages without full reloads.

It improves user experience by making navigation fast and smooth.

Angular routing uses routes to connect URLs to components.