Routing – Angular

Angular routing allows you to navigate between different views or components in a single-page application (SPA). It provides a way to configure routes and manage navigation, making your application more dynamic and user-friendly.

Setting Up Angular Routing

To set up routing in your Angular application, follow these steps:

  1. Install Angular Router (if not already included):
    If you set up your Angular project with routing, this step is not necessary. Otherwise, you can add routing manually:
   ng add @angular/router
  1. Define Routes:
    Create a routing module that defines the routes for your application.
   // app-routing.module.ts
   import { NgModule } from '@angular/core';
   import { RouterModule, Routes } from '@angular/router';
   import { HomeComponent } from './home/home.component';
   import { AboutComponent } from './about/about.component';

   const routes: Routes = [
     { path: '', component: HomeComponent },
     { path: 'about', component: AboutComponent },
   ];

   @NgModule({
     imports: [RouterModule.forRoot(routes)],
     exports: [RouterModule]
   })
   export class AppRoutingModule { }
  1. Import the Routing Module:
    Import the AppRoutingModule in your main application module.
   // app.module.ts
   import { BrowserModule } from '@angular/platform-browser';
   import { NgModule } from '@angular/core';
   import { AppRoutingModule } from './app-routing.module';
   import { AppComponent } from './app.component';
   import { HomeComponent } from './home/home.component';
   import { AboutComponent } from './about/about.component';

   @NgModule({
     declarations: [
       AppComponent,
       HomeComponent,
       AboutComponent
     ],
     imports: [
       BrowserModule,
       AppRoutingModule
     ],
     bootstrap: [AppComponent]
   })
   export class AppModule { }
  1. Create Components:
    Generate the components you will navigate to.
   ng generate component home
   ng generate component about
  1. Add Router Outlet:
    In your main template file (usually app.component.html), add the <router-outlet> directive where you want the routed component to be displayed.
   <!-- app.component.html -->
   <nav>
     <a routerLink="/">Home</a>
     <a routerLink="/about">About</a>
   </nav>
   <router-outlet></router-outlet>

Navigating Between Routes

  • Using RouterLink:
    Use the routerLink directive to link to different routes.
  <a routerLink="/about">About</a>
  • Programmatically Navigating:
    You can also navigate using the Router service.
  import { Component } from '@angular/core';
  import { Router } from '@angular/router';

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

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

Route Parameters

You can define routes that accept parameters.

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

// Accessing parameters in the component
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-user',
  template: '<p>User ID: {{ userId }}</p>'
})
export class UserComponent implements OnInit {
  userId: string;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.route.params.subscribe(params => {
      this.userId = params['id'];
    });
  }
}

Nested Routes

You can create nested routes by defining child routes.

// app-routing.module.ts
const routes: Routes = [
  {
    path: 'products',
    component: ProductsComponent,
    children: [
      { path: 'details/:id', component: ProductDetailsComponent }
    ]
  }
];

Route Guards

Route guards are used to protect routes and control access based on specific conditions.

  1. CanActivate Guard:
   import { Injectable } from '@angular/core';
   import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';

   @Injectable({
     providedIn: 'root'
   })
   export class AuthGuard implements CanActivate {
     constructor(private router: Router) {}

     canActivate(
       next: ActivatedRouteSnapshot,
       state: RouterStateSnapshot): boolean {
       const isLoggedIn = false; // Replace with your logic
       if (!isLoggedIn) {
         this.router.navigate(['/login']);
         return false;
       }
       return true;
     }
   }

To use the guard:

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

Lazy Loading

Lazy loading allows you to load modules only when they are needed, improving the initial load time of your application.

  1. Create a Feature Module:
   ng generate module feature --routing
  1. Define Routes in the Feature Module:
   // feature-routing.module.ts
   const routes: Routes = [
     { path: '', component: FeatureComponent }
   ];
  1. Lazy Load the Module:
   const routes: Routes = [
     { path: 'feature', loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule) }
   ];

Conclusion

Angular routing is a powerful feature that enhances the user experience in single-page applications. By setting up routes, navigating between them, and implementing features like route guards and lazy loading, you can create a robust and efficient Angular application.

Tags: No tags

Add a Comment

Your email address will not be published. Required fields are marked *