Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Take A QuizChallenge yourself and boost your learning! Start the quiz now to earn credits.
Take A QuizUnlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
Take A Quiz
Routing in Angular allows developers to build Single Page
Applications (SPAs) with multiple views while still serving content dynamically
without page reloads. This chapter dives into the Angular Router module, route
configuration, navigation, guards, lazy loading, route parameters, and much
more.
1. What is Routing in Angular?
Routing is the mechanism in Angular that lets you navigate
from one view to another within a single-page application.
Key Benefits:
2. Setting Up Angular Routing
When generating a new project with routing:
bash
ng new my-app --routing
This automatically adds app-routing.module.ts with default
imports.
ts
//
app-routing.module.ts
import
{ NgModule } from '@angular/core';
import
{ RouterModule, Routes } from '@angular/router';
const
routes: Routes = [];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export
class AppRoutingModule {}
3. Configuring Basic Routes
Let’s create two components:
bash
ng
generate component home
ng
generate component about
Add routes in app-routing.module.ts:
ts
const
routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent }
];
Use <router-outlet></router-outlet> in app.component.html
to display routed views:
html
<!--
app.component.html -->
<nav>
<a routerLink="/">Home</a>
<a routerLink="/about">About</a>
</nav>
<router-outlet></router-outlet>
4. RouterModule Methods
|
Method |
Description |
|
forRoot() |
Used in root module |
|
forChild() |
Used for
feature modules |
|
RouterLink |
Directive for template
navigation |
|
router.navigate() |
Programmatic
navigation |
5. Navigating with routerLink and router.navigate()
Template Navigation
html
<a
routerLink="/about">About</a>
Programmatic Navigation
ts
constructor(private
router: Router) {}
goToAbout()
{
this.router.navigate(['/about']);
}
6. Route Parameters
Parameters are used to pass values through routes.
Configuring Parameterized Routes
ts
const
routes: Routes = [
{ path: 'product/:id', component: ProductComponent
}
];
Accessing Parameters in Component
ts
constructor(private
route: ActivatedRoute) {}
ngOnInit()
{
this.route.params.subscribe(params => {
console.log(params['id']);
});
}
7. Query Parameters
Query parameters are useful for filters, sorts, etc.
Navigating with Query Params
ts
this.router.navigate(['/products'],
{ queryParams: { sort: 'price' } });
Accessing Query Params
ts
this.route.queryParams.subscribe(params
=> {
console.log(params['sort']);
});
8. Wildcard and Redirect Routes
|
Route Example |
Description |
|
{ path: '**', ... } |
Wildcard route
(catch-all) |
|
{ path: '', redirectTo: ..., pathMatch: 'full' } |
Redirect
routes |
Example
ts
const
routes: Routes = [
{ path:
'', redirectTo: '/home', pathMatch: 'full' },
{ path: '**', component: PageNotFoundComponent
}
];
9. Nested Routes (Child Routes)
Nested routes allow you to render components inside parent
components.
Parent Route
ts
const
routes: Routes = [
{
path: 'dashboard',
component: DashboardComponent,
children: [
{ path: 'stats', component: StatsComponent
},
{ path: 'reports', component: ReportsComponent
}
]
}
];
In Template
html
<nav>
<a routerLink="stats">Stats</a>
<a routerLink="reports">Reports</a>
</nav>
<router-outlet></router-outlet>
10. Route Guards
Angular guards protect routes from unauthorized access or
prevent navigating away with unsaved changes.
|
Guard Interface |
Purpose |
|
CanActivate |
Control access to a
route |
|
CanDeactivate |
Control
exiting a route |
|
Resolve |
Pre-fetch data before
loading |
Example: CanActivate
ts
@Injectable({
providedIn: 'root' })
export
class AuthGuard implements CanActivate {
constructor(private auth: AuthService, private
router: Router) {}
canActivate(): boolean {
if (this.auth.isLoggedIn()) return true;
this.router.navigate(['/login']);
return false;
}
}
Use it in routing:
ts
{
path: 'admin', component: AdminComponent, canActivate: [AuthGuard] }
11. Lazy Loading Modules
Lazy loading improves performance by loading modules only
when needed.
Create Feature Module
bash
ng
generate module features/products --route products --module app
This creates a lazy-loaded module.
ts
const
routes: Routes = [
{
path: 'products',
loadChildren: () =>
import('./features/products/products.module').then(m
=> m.ProductsModule)
}
];
12. Route Animations
You can animate route transitions using Angular’s Animation
API.
Setup Example
ts
trigger('routeAnimations',
[
transition('* <=> *', [
style({ opacity: 0 }),
animate('300ms ease-in', style({ opacity: 1
}))
])
])
Apply it in the router outlet:
html
<main
[@routeAnimations]="o.isActivated ? o.activatedRoute : ''">
<router-outlet #o="outlet"></router-outlet>
</main>
13. Preloading Strategies
Improve user experience by preloading lazy modules.
|
Strategy |
Description |
|
NoPreloading |
Default, no preloading |
|
PreloadAllModules |
Preloads all
lazy modules |
|
Custom Strategy |
Custom control over
preloading |
Setup
ts
RouterModule.forRoot(routes,
{
preloadingStrategy: PreloadAllModules
})
14. Router Events and Navigation Hooks
Listen to router events for advanced routing logic:
ts
this.router.events.subscribe(event
=> {
if (event instanceof NavigationStart) {
console.log('Navigation Started');
}
});
15. Using Route Resolvers
Resolvers fetch data before the route loads.
Create Resolver
ts
@Injectable({
providedIn: 'root' })
export
class ProductResolver implements Resolve<Product> {
constructor(private productService:
ProductService) {}
resolve(route: ActivatedRouteSnapshot): Observable<Product>
{
return this.productService.getProduct(route.params['id']);
}
}
Add to route:
ts
{
path: 'product/:id', component: ProductComponent, resolve: { product: ProductResolver
} }
Access via:
ts
this.route.data.subscribe(data
=> {
this.product = data['product'];
});
✅ Chapter Summary
|
Feature |
Purpose |
|
routerLink |
Declarative navigation |
|
router.navigate() |
Programmatic
navigation |
|
ActivatedRoute |
Access route
parameters |
|
CanActivate |
Guard to
allow/deny access |
|
Resolve |
Fetch data before
loading component |
|
Lazy Loading |
Performance
optimization |
Angular routing is not just about navigation; it's a full-blown framework for managing application views, access, data preloading, and module optimization.
BackA: Yes, but having a basic understanding of TypeScript and JavaScript ES6 will help a lot.
A: Angular uses TypeScript, which is a superset of JavaScript.
A: AngularJS (1.x) is the older version using JavaScript, while Angular (2+) uses TypeScript and a component-based architecture.
A: Yes, with frameworks like Ionic or NativeScript.
A: Angular is a full framework with built-in tools, while React is a library focused on UI.
A: Yes, Angular excels in large, structured, maintainable apps.
A: It’s a command-line tool that helps scaffold, develop, and manage Angular applications efficiently.
A: Yes, Node.js is required to install Angular CLI and manage dependencies.
A: A reusable unit of UI that consists of a template, logic, and styling.
A: Yes, Angular can be paired with any backend via APIs.
Please log in to access this content. You will be redirected to the login page shortly.
Login
Ready to take your education and career to the next level? Register today and join our growing community of learners and professionals.
Your experience on this site will be improved by allowing cookies. Read Cookie Policy
Your experience on this site will be improved by allowing cookies. Read Cookie Policy
Comments(0)