Routing in Angular
Routing in Angular is used to navigate between different views/components in a Single Page Application (SPA) without reloading the entire page.
Instead of requesting a new HTML page from the server, Angular dynamically loads components based on the URL.
1. What is Angular Routing?
Angular Routing allows users to navigate between components using URLs.
Example:
/home
/about
/products
/products/10
Each URL is mapped to a specific Angular component.
2. Why Routing is Needed?
Routing helps in:
-
Building SPA applications
-
Navigation without page refresh
-
Bookmarkable URLs
-
Lazy loading modules
-
Route protection using guards
-
Passing parameters in URL
-
Better user experience
3. How Routing Works Internally
Angular uses:
-
RouterModule -
Routes -
RouterOutlet -
Router
Flow
-
User enters a URL
-
Angular Router checks route configuration
-
Matching route is identified
-
Corresponding component is loaded
-
Component is rendered inside
<router-outlet>
4. Basic Routing Setup
Step 1 — Define Routes
// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
Step 2 — Add Router Outlet
<!-- app.component.html -->
<router-outlet></router-outlet>
router-outlet acts as a placeholder where routed components are loaded dynamically.
Step 3 — Navigation Links
<a routerLink="/home">Home</a>
<a routerLink="/about">About</a>
5. Important Routing Concepts
A. RouterModule.forRoot()
Used in root module.
RouterModule.forRoot(routes)
It configures application-level routes.
B. RouterModule.forChild()
Used in feature modules.
RouterModule.forChild(routes)
Mostly used with lazy loading.
C. Route Interface
Each route object contains:
{
path: '',
component: HomeComponent
}
Common properties:
| Property | Purpose |
|---|---|
| path | URL path |
| component | Component to load |
| redirectTo | Redirect URL |
| children | Child routes |
| loadChildren | Lazy loading |
| canActivate | Route guard |
6. Route Parameters
Used to pass dynamic values.
Example:
/products/101
Route Configuration
{
path: 'products/:id',
component: ProductComponent
}
Access Parameter
import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) {}
ngOnInit() {
const id = this.route.snapshot.paramMap.get('id');
console.log(id);
}
7. Query Parameters
Example:
/products?id=10
Navigation
this.router.navigate(['/products'], {
queryParams: { id: 10 }
});
Reading Query Params
this.route.queryParams.subscribe(params => {
console.log(params['id']);
});
8. Route Navigation
Using routerLink
<a routerLink="/home">Home</a>
Using Router Service
constructor(private router: Router) {}
goToHome() {
this.router.navigate(['/home']);
}
9. Redirect Routes
{
path: '',
redirectTo: 'home',
pathMatch: 'full'
}
pathMatch: 'full' ensures exact path matching.
10. Wildcard Route
Used for 404 pages.
{
path: '**',
component: NotFoundComponent
}
Must always be the last route.
11. Child Routing
Used for nested routes.
Example
{
path: 'admin',
component: AdminComponent,
children: [
{
path: 'users',
component: UsersComponent
},
{
path: 'settings',
component: SettingsComponent
}
]
}
Parent component must contain:
<router-outlet></router-outlet>
12. Lazy Loading
Loads feature modules only when required.
Improves performance.
Example
{
path: 'admin',
loadChildren: () =>
import('./admin/admin.module')
.then(m => m.AdminModule)
}
13. Route Guards
Used to protect routes.
Types:
| Guard | Purpose |
|---|---|
| CanActivate | Allow/deny route access |
| CanDeactivate | Prevent leaving page |
| Resolve | Fetch data before loading |
| CanLoad | Prevent lazy module loading |
Example — CanActivate
@Injectable()
export class AuthGuard implements CanActivate {
canActivate(): boolean {
return isLoggedIn();
}
}
Route:
{
path: 'dashboard',
component: DashboardComponent,
canActivate: [AuthGuard]
}
14. Router Events
Angular router emits events during navigation.
Example:
this.router.events.subscribe(event => {
console.log(event);
});
Common events:
-
NavigationStart
-
NavigationEnd
-
NavigationCancel
-
NavigationError
15. Difference Between href and routerLink
| href | routerLink |
|---|---|
| Reloads page | No page reload |
| Browser navigation | Angular navigation |
| Traditional websites | SPA applications |
16. Hash-Based vs Path-Based Routing
Hash Routing
example.com/#/home
Uses:
RouterModule.forRoot(routes, { useHash: true })
Path Routing
example.com/home
Default and preferred approach.
17. Routing Lifecycle
Angular routing flow:
URL Change
↓
Route Match
↓
Guards Execution
↓
Resolvers
↓
Component Loading
↓
View Rendered
18. Common Interview Questions
Q1. What is Angular Routing?
Routing enables navigation between views/components in SPA without full page reload.
Q2. What is router-outlet?
Placeholder where routed components are dynamically loaded.
Q3. Difference between forRoot() and forChild()?
| forRoot | forChild |
|---|---|
| Root module | Feature modules |
| Configures app router | Configures child routes |
Q4. What is Lazy Loading?
Feature modules are loaded only when required to improve performance.
Q5. Difference between Route Params and Query Params?
| Route Params | Query Params |
|---|---|
| Required | Optional |
/product/10 |
/product?id=10 |
19. Real-Time Example
Imagine an e-commerce app:
| URL | Component |
|---|---|
/home |
HomeComponent |
/products |
ProductListComponent |
/products/10 |
ProductDetailComponent |
/cart |
CartComponent |
/admin |
Lazy-loaded AdminModule |
20. Best Practices
-
Use lazy loading for large modules
-
Use guards for protected routes
-
Keep routing modular
-
Use route resolvers for preloading data
-
Use wildcard route for 404 handling
-
Avoid deeply nested routing
Interview Summary (Short Answer)
Angular Routing is a mechanism used to navigate between components in a Single Page Application without reloading the page. Angular Router matches URLs with configured routes and dynamically loads components inside
router-outlet. Features include lazy loading, route guards, child routing, route parameters, and navigation using Router service or routerLink.
