Angular Router
Learn Angular Router, including SPA routing, route configuration, router-outlet, routerLink, programmatic navigation, route parameters, query parameters, child routes, redirects, wildcard routes, guards, lazy loading, resolvers, and enterprise routing architecture.
Learning Objectives
By the end of this lesson, you will understand:
- What routing means in Angular and why it is essential for Single Page Applications.
- How Angular Router, route configuration,
router-outlet, androuterLinkwork. - How to use programmatic navigation, route parameters, query parameters, redirects, wildcard routes, and child routes.
- How route guards, lazy loading, route data, and resolvers fit into enterprise routing architecture.
- Why frontend guards are not a backend security boundary.
Introduction
Imagine you're building an e-commerce application with pages such as Home, Products, Product Details, Cart, Checkout, Orders, and Profile.
Users expect meaningful URLs:
//products/products/101/cart/checkout/orders/profile
Traditional websites may request a new HTML document from the server for every navigation. Angular applications commonly follow the Single Page Application model: the application shell loads once, and Angular dynamically changes the displayed view based on the URL.
This is the responsibility of the Angular Router.
A Real-World Story
Imagine you're building an enterprise banking application with routes such as:
/dashboard/accounts/accounts/12345/transactions/beneficiaries/payments/profile/admin
Browser URL│▼Angular Router│▼Route Configuration│▼Matching Component│▼router-outlet│▼Page Displayed
The Router becomes an important part of the application's overall architecture because URLs, views, authentication checks, lazy features, and navigation state all meet there.
What Is Angular Router?
Angular Router is Angular's official navigation library for managing application views based on browser URLs.
It supports route configuration, URL-based navigation, route parameters, query parameters, nested routes, redirects, lazy loading, route guards, navigation events, route data, and route resolvers.
URL│▼Router│▼Route Match│▼Component│▼Rendered View
Single Page Application Routing
In a traditional multi-page website, navigation often triggers a browser request, server response, new HTML page, and full page reload.
In an Angular SPA, Angular Router updates the URL, matches a route, and renders the matching component without reloading the whole application during normal client-side navigation.
Basic Route Configuration
import { Routes } from '@angular/router';import { HomeComponent } from './home/home.component';import { ProductsComponent } from './products/products.component';import { CartComponent } from './cart/cart.component';export const routes: Routes = [{ path: '', component: HomeComponent },{ path: 'products', component: ProductsComponent },{ path: 'cart', component: CartComponent }];
Now Angular understands that /, /products, and /cart map to specific components.
Providing the Router
In a modern standalone Angular application, the router can be provided during application bootstrap.
import { bootstrapApplication } from '@angular/platform-browser';import { provideRouter } from '@angular/router';import { AppComponent } from './app/app.component';import { routes } from './app/app.routes';bootstrapApplication(AppComponent, {providers: [provideRouter(routes)]});
In module-based Angular applications, you may encounter RouterModule.forRoot().
Understanding router-outlet
Defining routes is not enough. Angular needs to know where routed components should appear.
<header>My Application</header><nav>Navigation</nav><main><router-outlet /></main><footer>Copyright</footer>
Only the routed content changes; the surrounding application shell remains.
Router Architecture
Router Flow
Browser URL to User View
Navigating with routerLink
For internal Angular routes, use routerLink.
<a routerLink="/">Home</a><a routerLink="/products">Products</a><a routerLink="/cart">Cart</a>
Why Not Use href Everywhere?
href performs normal browser navigation and may reload the app depending on usage. Use routerLink for internal Angular routes and regular href for external websites.
Active Route Styling
<arouterLink="/products"routerLinkActive="active">Products</a>
When the route is active, Angular applies the active CSS class.
Programmatic Navigation
Sometimes navigation happens because of application logic, such as after login or order completion.
import { Router } from '@angular/router';export class LoginComponent {constructor(private router: Router) {}login(): void {// Authentication logicthis.router.navigate(['/dashboard']);}}
Real-World Login Flow
User Opens Login│▼/login│▼Enters Credentials│▼Authentication API│┌───┴────┐▼ ▼Success Failure│ │▼ ▼Navigate Show Error│▼/dashboard
Route Parameters
Use route parameters for dynamic resources.
{path: 'products/:id',component: ProductDetailsComponent}
URLs like /products/101 and /products/500 share the same route shape.
Route Parameter Architecture
/products/101│▼Angular Router│▼products/:id│▼id = 101│▼ProductDetailsComponent│▼Product Service│▼Backend API
Reading Route Parameters
import { ActivatedRoute } from '@angular/router';export class ProductDetailsComponent {constructor(private route: ActivatedRoute) {}ngOnInit(): void {const productId = this.route.snapshot.paramMap.get('id');console.log(productId);}}
Snapshot vs Observable Route Parameters
snapshot provides route state at a particular moment. The observable form is useful when parameters can change while Angular continues using the same component instance.
this.route.paramMap.subscribe(params => {const id = params.get('id');this.loadProduct(id);});
Query Parameters
Query parameters commonly represent optional view state such as filters, search terms, sorting, and pagination.
/products?category=laptop&page=2
Navigating with Query Parameters
this.router.navigate(['/products'],{queryParams: {category: 'laptop',page: 2}});
Reading Query Parameters
this.route.queryParamMap.subscribe(params => {const category = params.get('category');const page = params.get('page');});
Query parameters are especially useful for shareable search and filtering state.
Route Parameters vs Query Parameters
| Route Parameter | Query Parameter |
|---|---|
/products/101 | /products?page=2 |
| Usually identifies a resource | Usually modifies a view |
| Often required | Often optional |
Route Redirects
{path: '',redirectTo: 'home',pathMatch: 'full'}
pathMatch: 'full' is important for empty-path redirects.
Wildcard Routes and 404 Pages
{path: '**',component: NotFoundComponent}
This route should normally appear at the end of the route configuration.
Child Routes
Large applications often contain nested sections.
{path: 'account',component: AccountComponent,children: [{ path: 'profile', component: ProfileComponent },{ path: 'security', component: SecurityComponent },{ path: 'preferences', component: PreferencesComponent }]}
The parent component typically contains another <router-outlet /> for child routes.
Nested Routing Architecture
AppComponent│▼Main router-outlet│▼AccountComponent│├── Account Navigation└── Child router-outlet│├── ProfileComponent├── SecurityComponent└── PreferencesComponent
Route Guards
Route Guards participate in navigation decisions, such as authentication checks, role-based navigation, unsaved form warnings, feature access, and conditional navigation.
User Navigates│▼Route Guard│┌───┴────┐▼ ▼Allow Deny│ │▼ ▼Route Redirect
Authentication Guard Example
export const authGuard = () => {const authService = inject(AuthService);const router = inject(Router);if (authService.isLoggedIn()) {return true;}return router.createUrlTree(['/login']);};
{path: 'dashboard',component: DashboardComponent,canActivate: [authGuard]}
Important Security Principle
Route Guards are useful for navigation and user experience, but they do not secure backend APIs.
Angular Route Guard -> Controls Frontend NavigationBackend Authorization -> Controls Actual Resource Access
The backend must always enforce authorization independently.
Lazy Loading
As applications grow, loading every feature immediately can hurt startup performance. Lazy loading allows Angular to load feature code when it is needed.
Lazy Loading Architecture
Application Starts│▼Load Core Application│▼User Opens Dashboard│▼Dashboard Available│▼User Opens Admin│▼Load Admin Feature
Lazy Loading a Standalone Component
{path: 'reports',loadComponent: () =>import('./reports/reports.component').then(m => m.ReportsComponent)}
Lazy Loading Feature Routes
{path: 'admin',loadChildren: () =>import('./admin/admin.routes').then(m => m.ADMIN_ROUTES)}
Enterprise Routing Architecture
App Router│├── Public Routes├── Protected Routes├── Lazy Features└── Admin Routes
Large applications should organize routes by business feature instead of placing hundreds of routes in one file.
Route Resolvers
A resolver can load route-related data before a routed component is activated. Use resolvers thoughtfully: if loading takes a long time, displaying a loading state inside the page may be preferable.
Unsaved Changes Protection
Navigation guard patterns such as CanDeactivate can warn users before leaving forms with unsaved changes.
User Navigates Away│▼Unsaved Changes?/ \No Yes│ │▼ ▼Navigate Ask User
Route Data
{path: 'admin',component: AdminComponent,data: {title: 'Administration',requiredRole: 'ADMIN'}}
Route data can support page titles, breadcrumbs, navigation metadata, and feature configuration. Metadata alone does not enforce security.
Real-World Case Study: E-Commerce Routing
//products/products/101/cart/checkout/orders/orders/5001/admin/products/admin/orders
The router becomes the navigation backbone of the entire frontend.
Routing and Authentication Flow
User Requests Protected Route│▼Auth Guard│┌─────┴─────┐▼ ▼Authenticated Not Authenticated│ │▼ ▼Continue Redirect Login│▼Login│▼Authentication│▼Navigate to Intended Route
Routing and Browser Refresh
If a user directly opens /products/101, the production web server must be configured to serve the Angular app entry point for appropriate client-side routes. Then Angular Router can process the URL after startup.
Route Design Best Practices
- Keep URLs meaningful.
- Use query parameters for optional view state.
- Lazy-load large features.
- Use guards for navigation flow, but enforce authorization on the backend.
- Add a 404 route.
- Organize route configuration by feature.
Common Pitfalls
Putting the Wildcard Route First
The wildcard can capture routes before intended routes are reached. Keep it last.
Treating Route Guards as Security
Frontend guards can be bypassed. Backend authorization is mandatory.
Forgetting router-outlet
Routes need an outlet where routed content can render.
Overusing Snapshot Parameters
If parameters can change while the same component remains active, use reactive route parameter APIs.
Loading Every Feature Eagerly
Use lazy loading strategically for large applications.
Ignoring Server Configuration
Client-side routing may work in development but fail on deep URL refreshes in production if hosting is not configured for SPA routing.
Common Misconceptions
Misconception
Angular Router sends every navigation request to the backend.
Reality
Normal Angular SPA navigation is primarily handled client-side after the application has loaded.
Misconception
routerLink and href are always identical.
Reality
routerLink integrates with Angular Router for internal navigation, while href performs normal browser navigation.
Misconception
A Route Guard protects the backend.
Reality
Route Guards control frontend navigation. Backend APIs require independent authentication and authorization.
Misconception
Lazy loading means API data is lazy loaded.
Reality
Router lazy loading primarily concerns JavaScript application code. API data loading is separate.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhat is Angular Router?+
Answer
2BeginnerQuestionWhat is router-outlet?+
Answer
3BeginnerQuestionWhat is routerLink?+
Answer
4BeginnerQuestionWhat is the difference between routerLink and Router.navigate()?+
Answer
5IntermediateQuestionWhat are route parameters?+
Answer
6IntermediateQuestionWhat is the difference between route parameters and query parameters?+
Answer
7IntermediateQuestionWhat is lazy loading?+
Answer
8IntermediateQuestionWhat are Route Guards?+
Answer
9AdvancedQuestionWhat is a wildcard route?+
Answer
10AdvancedQuestionWhy should the wildcard route usually be last?+
Answer
11AdvancedQuestionWhat is the difference between eager loading and lazy loading?+
Answer
12AdvancedQuestionWhat happens when a user refreshes a deep Angular route?+
Answer
13AdvancedQuestionHow would you design routing for a large enterprise application?+
Answer
Summary
Angular Router connects the browser URL with the application's user interface.
URL│▼Angular Router│▼Route Configuration│▼Component│▼router-outlet
In production applications, routing defines how users navigate, bookmark, share, access, and experience different areas of the application.
When combined with meaningful URLs, lazy loading, feature-based route organization, route parameters, query parameters, guards, and proper backend authorization, Angular Router provides the foundation for scalable Single Page Applications.
Next Lesson: Angular Services & Dependency Injection - you'll learn how Angular separates business logic from components, how services share data across the application, how Dependency Injection works internally, how providedIn: 'root' creates application-level services, how hierarchical injectors work, and how enterprise Angular applications structure API, domain, state, and utility services.