Learn Angular Router: Comprehensive Tutorial with Examples
Master Angular Router with our detailed tutorial. From basic setup to advanced concepts, understand navigation, routing, route parameters, guards, lazy loading, and more. Real-world examples provided.
Angular Router Tutorial: Mastering Navigation and Routing
In this comprehensive tutorial, we will delve into the world of Angular Router, an essential feature of the Angular framework that enables navigation and routing within your single-page applications. We'll cover everything from the basics to advanced concepts, providing clear definitions and real-world examples along the way.
Table of Contents
- Introduction to Angular Router
- Setting Up the Router
- Creating Routes
- Navigating Between Routes
- Route Parameters and Wildcards
- Child Routes and Nested Navigation
- Router Guards
- Lazy Loading Modules
- Auxiliary Routes
- Handling Query Parameters
- Programmatic Navigation
- Route Resolvers
- Customizing Route Matching Strategies
- Location Strategies
1. Introduction to Angular Router
Angular Router is a powerful feature that enables navigation and routing within single-page applications. It helps manage different views or components in response to user actions like clicking links, entering URLs, or pressing the browser's back and forward buttons. The router provides a way to render different components based on the current URL, enabling a seamless user experience.
2. Setting Up the Router
To use Angular Router, make sure you have an Angular application set up. You can create a new application using the Angular CLI:
ng new my-router-app
Once your application is set up, navigate to the app.module.ts
file and import the RouterModule
:
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
@NgModule({
imports: [RouterModule.forRoot([])], // Configure routes here
exports: [RouterModule]
})
export class AppModule { }
3. Creating Routes
Routes define the association between URLs and components. In your app.module.ts
, import the components you want to associate with routes and define your routes using the Routes
array:
typescriptCopy code
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'contact', component: ContactComponent },
];
4. Navigating Between Routes
To navigate between routes, use the routerLink
directive in your templates:
<a routerLink="/">Home</a>
<a routerLink="/about">About</a>
<a routerLink="/contact">Contact</a>
5. Route Parameters and Wildcards
Route parameters allow passing data through URLs. Define parameters in routes and access them in components:
// In routes
{
path: 'user/:id', component: UserComponent
}
// In UserComponent
ngOnInit()
{
this.route.params.subscribe(params => {
this.userId = params['id'];
});
}
Wildcards capture unmatched URLs for custom handling:
// In routes
{
path: '**',
component: NotFoundComponent
}
6. Child Routes and Nested Navigation
Child routes enable hierarchical navigation structures:
{
path: 'products',
component: ProductsComponent,
children: [
{
path: 'details/:id',
component: ProductDetailsComponent
},
{
path: 'edit/:id',
component: EditProductComponent
},
]}
7. Router Guards
Guards protect routes, enforcing conditions before navigation:
CanActivate
: Allow navigation based on a condition.CanDeactivate
: Confirm navigation away from a route.Resolve
: Fetch data before navigating to a route.
8. Lazy Loading Modules
Improve app performance by loading modules only when needed:
{
path: 'admin',
loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule)
}
9. Auxiliary Routes
Display multiple router outlets on the same page:
<router-outlet></router-outlet> <router-outlet name="sidebar"></router-outlet>
{
path: 'dashboard',
component: DashboardComponent,
outlet: 'sidebar'
}
10. Handling Query Parameters
Access and manipulate query parameters in components:
// Navigating with query parameters
this.router.navigate(['/search'], {
queryParams: { q: 'angular' }
});
// Accessing query parameters
this.route.queryParams.subscribe(params => { this.query = params['q']; });
11. Programmatic Navigation
Navigate programmatically using the Router
service:
constructor(private router: Router) {}
goToAbout() {
this.router.navigate(['/about']);
}
12. Route Resolvers
Resolve data before rendering a route's component:
{
path: 'user/:id',
component: UserComponent,
resolve: {
userData: UserResolver
}
}
// In UserResolver
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
return this.userService.getUser(route.params['id']);
}
13. Customizing Route Matching Strategies
Change how routes are matched using custom strategies.
14. Location Strategies
Choose how Angular handles browser history:
PathLocationStrategy
: Uses the URL path.HashLocationStrategy
: Uses the URL hash.MemoryLocationStrategy
: Doesn't affect the browser URL.
Conclusion
Angular Router is an indispensable tool for creating dynamic and user-friendly single-page applications. By mastering its concepts, you'll be able to craft seamless navigation experiences for your users, making your Angular applications truly shine.