Routing in Angular

Routing is a core feature in Angular that allows developers to create single-page applications (SPAs) by navigating between components and passing data through URLs. In this blog, we'll cover:

  1. Angular Router basics
  2. Navigating between components
  3. Passing parameters in routes
  4. Nested routes and route guards

1. Angular Router Basics

The Angular Router is a powerful library that enables navigation and deep linking within an Angular application. It maps URLs to components and defines the structure of the app's navigation system.

To set up routing, follow these steps:

Step 1: Import the Router Module


import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  { path: '', component: HomeComponent }, // Default route
  { path: 'about', component: AboutComponent }, // About page
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}
            

The RouterModule.forRoot(routes) method configures the app’s routes. Each route is defined as an object with a path and a corresponding component.

In the @NgModule decorator, the imports array is used to include modules needed for the current module. The exports array specifies what parts of this module should be available to other modules.

2. Navigating Between Components

There are two main ways to navigate between components in Angular:

Using Router Links

The routerLink directive binds a URL to an element. Clicking the element navigates to the route:


<a routerlink="/about">Go to About</a>
            

Using the Router Service

The Router service allows programmatic navigation within the application. For example:


import { Router } from '@angular/router';

@Component({
  selector: 'app-home',
  template: '<button click="" gotoabout="">Go to About</button>',
})
export class HomeComponent {
  constructor(private router: Router) {}

  goToAbout(): void {
    this.router.navigate(['/about']);
  }
}
            

3. Passing Parameters in Routes

Angular allows passing parameters in routes to make navigation more dynamic. This can be done using route parameters or query parameters.

Route Parameters

To define a route with a parameter, include a placeholder in the path:


const routes: Routes = [
  { path: 'user/:id', component: UserComponent },
];
            

Access the parameter in the component using the ActivatedRoute service:


import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-user',
  template: `

User ID: {{ userId }}

`, }) export class UserComponent { userId: string; constructor(private route: ActivatedRoute) { this.userId = this.route.snapshot.paramMap.get('id') || ''; } }

Query Parameters

Query parameters can be appended to the URL:


this.router.navigate(['/search'], { queryParams: { q: 'Angular' } });
            

Read query parameters in the component:


import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-search',
  template: `

Search Query: {{ query }}

`, }) export class SearchComponent { query: string; constructor(private route: ActivatedRoute) { this.query = this.route.snapshot.queryParamMap.get('q') || ''; } }

4. Nested Routes and Route Guards

Nested Routes

Angular supports nested routes, which allow defining child routes inside a parent route. This is useful for creating hierarchical navigation structures.


const routes: Routes = [
  {
    path: 'admin',
    component: AdminComponent,
    children: [
      { path: 'dashboard', component: DashboardComponent },
      { path: 'settings', component: SettingsComponent },
    ],
  },
];
            

To display child routes, use the <router-outlet> directive in the parent component:


<router-outlet></router-outlet>
            

Route Guards

Route guards are used to control access to routes. Common types include:

  • CanActivate: Determines whether a route can be activated.
  • CanDeactivate: Checks if a route can be left.
  • Resolve: Pre-fetches data before navigating to a route.

To implement a guard, create a service that implements the CanActivate interface:


import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';

@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate {
  canActivate(): boolean {
    const isLoggedIn = true; // Replace with actual logic
    return isLoggedIn;
  }
}
            

Apply the guard to a route:


const routes: Routes = [
  { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
];
            

Conclusion

Routing in Angular is a powerful way to create dynamic and modular single-page applications. By mastering the Angular Router, navigating between components, passing parameters, and using features like nested routes and route guards, you can build scalable and secure applications. Experiment with these features to take your Angular applications to the next level!

Post a Comment

0 Comments