Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Routing and Navigation in Angular

Routing and navigation are key aspects of single-page applications (SPAs). Angular provides a robust routing module that allows you to define routes and navigate between different views or components. This tutorial provides an overview of Angular routing and navigation, its key features, and how to set it up and use it effectively.

Setting Up Angular Routing

To use Angular routing, you need to import the RouterModule and configure the routes in your application's main module:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';

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

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    AboutComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Defining Routes

Routes are defined as an array of objects, where each object represents a route and its associated component. Here is an example of defining routes for a simple application with a home and about page:

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

Router Outlet

The <router-outlet> directive acts as a placeholder for the routed components. You need to add this directive to your main template:

<nav>
  <a routerLink="/">Home</a>
  <a routerLink="/about">About</a>
</nav>
<router-outlet></router-outlet>

Navigation

Angular provides several ways to navigate between routes, including the routerLink directive and the Router service:

<!-- Using routerLink directive -->
<a routerLink="/">Home</a>
<a routerLink="/about">About</a>

<!-- Using 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 route parameters to pass data to routed components. Here is an example of defining and using route parameters:

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

// Accessing route 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(): void {
    this.userId = this.route.snapshot.paramMap.get('id');
  }
}

Lazy Loading

Lazy loading allows you to load feature modules on demand, improving the initial load time of your application. Here is an example of configuring lazy loading for a feature module:

const routes: Routes = [
  { path: 'feature', loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule) }
];

Route Guards

Route guards allow you to control access to routes based on certain conditions. Here is an example of creating and using a route guard:

// AuthGuard service
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';

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

  canActivate(): boolean {
    const isAuthenticated = false; // Replace with actual authentication check
    if (!isAuthenticated) {
      this.router.navigate(['/login']);
      return false;
    }
    return true;
  }
}

// Using the route guard
const routes: Routes = [
  { path: 'protected', component: ProtectedComponent, canActivate: [AuthGuard] }
];

Conclusion

Routing and navigation are essential for building single-page applications in Angular. By understanding how to set up routes, navigate between them, and use advanced features like route parameters, lazy loading, and route guards, you can create dynamic and user-friendly applications. Happy coding!