Routing in Angular is a crucial aspect of building single-page applications (SPAs) that enable navigation between different views or components without full page reloads. Here's a basic rundown:
Setting Up Routes:
-
Import Routes and RouterModule: In your Angular app module file (
app.module.ts
), importRoutes and RouterModule
from@angular/router
. -
Define Routes: Create an array of route objects where each route specifies a path and the component it should display. For example:
const routes: Routes = [ { path: '', redirectTo: '/home', pathMatch: 'full' }, // Default route { path: 'home', component: HomeComponent }, { path: 'about', component: AboutComponent }, // Add more routes as needed ];
-
Configure RouterModule: Use
RouterModule.forRoot()
to configure the routes in your app module'simports
array:@NgModule({ imports: [ RouterModule.forRoot(routes) // Other module imports ], // Other configurations })
Using Router Outlet
In your main template file (app.component.html
by default), include the
<router-outlet></router-outlet>
Navigation
-
RouterLink Directive: Use the routerLink directive in your templates to navigate to different routes. For example:
<a routerLink="/home">Home</a> <a routerLink="/about">About</a>
-
Programmatic Navigation: In your component classes, you can use the
Router
service to navigate programmatically:import { Router } from '@angular/router'; constructor(private router: Router) {} goToAboutPage() { this.router.navigate(['/about']); }
Route Parameters
You can define routes with parameters to handle dynamic data. For example:
{ path: 'users/:id', component: UserComponent }
And in your component, access the parameter using ActivatedRoute
:
import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) {
this.route.params.subscribe(params => {
const userId = params['id'];
// Use userId to fetch user data or perform actions
});
}
Route Guards
You can implement guards to control access to certain routes based on conditions (e.g., authentication) using CanActivate, CanActivateChild, CanDeactivate,
etc.
Angular's routing system provides a lot of flexibility and power in managing navigation within your application, allowing for both simple and complex navigation structures.