All About Routing in Angular

Dipak ahir
3 min readOct 8, 2023

--

Routing in Angular is a fundamental concept that allows you to build single-page applications (SPAs) with multiple views or pages, all within a single HTML page. It enables navigation between different components or views while maintaining the application state.

Here’s a detailed overview of routing in Angular:

1. Setting Up Routes:

  • RouterModule: To enable routing in your Angular application, you need to import the RouterModule and configure it in your main app module.
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'products', component: ProductsComponent },
{ path: 'about', component: AboutComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: '**', component: NotFoundComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}

In this example, an array of route configurations is defined. Each configuration specifies a route path and the component to display when the route is activated. You can also define redirects and a wildcard route for handling unknown paths.

2. Router Outlet:

  • To render components associated with routes, you need to add a <router-outlet></router-outlet> element in your main app component's template. This is where the activated component will be displayed.
<router-outlet></router-outlet>

3. Navigating Between Routes:

  • You can navigate to different routes using the RouterLink directive in your templates.
<a routerLink="/home">Home</a>
<a routerLink="/products">Products</a>
<a routerLink="/about">About</a>
  • Programmatically, you can use the Router service for navigation in component code.
import { Router } from '@angular/router';
constructor(private router: Router) {}
navigateToProducts() {
this.router.navigate(['/products']);
}

4. Route Parameters:

  • Routes can have parameters to pass data between components. You define route parameters in the route configuration.
const routes: Routes = [
{ path: 'products/:id', component: ProductDetailComponent },
];
  • Access route parameters in a component using ActivatedRoute.
import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) {
this.route.params.subscribe(params => {
this.productId = params['id'];
});
}

5. Child Routes:

  • You can create nested or child routes to organize your application’s routes hierarchically.
const routes: Routes = [
{
path: 'products',
component: ProductsComponent,
children: [
{ path: 'list', component: ProductListComponent },
{ path: 'detail/:id', component: ProductDetailComponent },
],
},
];

6. Route Guards:

  • Route guards protect routes based on conditions. Angular provides several types of guards like CanActivate, CanDeactivate, CanLoad, and Resolve.

7. Lazy Loading:

  • Lazy loading allows you to load parts of your application on-demand, reducing initial loading times. You configure lazy-loaded routes using the loadChildren property.
const routes: Routes = [
{
path: 'admin',
loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule),
},
];

8. Router Events:

  • Angular’s Router emits events that you can subscribe to, allowing you to perform actions based on route changes. Common events include NavigationStart, NavigationEnd, and NavigationError.

9. Location Strategies:

  • As mentioned earlier, Angular supports different location strategies, such as PathLocationStrategy and HashLocationStrategy, to determine how route URLs are displayed and handled.

10. Route Configuration in HTML:

  • You can also configure routes directly in HTML using the [routerLink] directive and the router-outlet element. This approach is known as "RouterLink DSL."
<a [routerLink]="['/products']">Products</a>
<router-outlet></router-outlet>

Routing in Angular is a powerful tool for building complex single-page applications with structured navigation. It allows you to create clean, maintainable, and organized code for managing different views and components within your application.

--

--