In Angular, routing is the process of navigating between different views (or components) based on a URL and the associated path. It is a crucial aspect of single-page applications (SPA) that allows users to navigate between views without reloading the entire page.

The Angular Router is used to set up routing in Angular applications, and it is included in the @angular/router package.

Key Features of Angular Routing:

  1. Component Route and Path: Defines which component should be displayed for a specific URL (path).

  2. Router Outlet: A placeholder where the routed component will be displayed in the view.

  3. Route Matching Strategies: Determines how the router matches the route to the URL.

  4. Route Parameters: Parameters in the URL that can be passed to the route to display dynamic content.

  5. Query Parameters: Parameters appended to the URL (e.g., /path?name=John).

  6. Route Guards: Prevents or allows navigation based on conditions (e.g., authentication).

  7. Route Resolvers: Pre-fetch data before navigating to a route.

  8. RouteLink Directive: A directive used for navigating between routes, replacing the traditional anchor (<a href="...">) tag.

  9. Auxiliary Routes: Allows multiple views to be displayed in different parts of the UI simultaneously.

  10. Primary and Secondary Router Outlets: Supports multiple router outlets, enabling more complex page structures.


1. Component Route and Path

This feature maps a specific URL path to a component. When the user navigates to the URL, the corresponding component is displayed.

Example:

// 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 },  // Default path
  { path: 'about', component: AboutComponent }  // About page route
];
 
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}
<!-- app.component.html -->
<nav>
  <a routerLink="/">Home</a>
  <a routerLink="/about">About</a>
</nav>
 
<router-outlet></router-outlet> <!-- This is where routed components will appear -->

2. Router Outlet

The <router-outlet> is where the routed components will be displayed when the user navigates to a particular route.

Example:

<!-- app.component.html -->
<h1>Welcome to Our Site</h1>
<router-outlet></router-outlet>  <!-- Routed components will be displayed here -->

3. Route Matching Strategies

Angular provides two strategies for matching routes: Prefix and Full. prefix matches the route based on the initial part of the URL, while full matches the entire URL.

Example:

const routes: Routes = [
  { path: 'home', component: HomeComponent, pathMatch: 'full' },  // Matches the whole URL exactly
  { path: 'about', component: AboutComponent, pathMatch: 'prefix' }  // Matches based on prefix
];

4. Route Parameters

Route parameters are dynamic segments in the route that are passed through the URL. These parameters can be accessed inside the component.

Example:

// app-routing.module.ts
const routes: Routes = [
  { path: 'profile/:id', component: ProfileComponent }  // Define parameterized route
];
// profile.component.ts
import { ActivatedRoute } from '@angular/router';
 
@Component({
  selector: 'app-profile',
  template: `<h2>Profile ID: {{ profileId }}</h2>`
})
export class ProfileComponent implements OnInit {
  profileId: string;
 
  constructor(private route: ActivatedRoute) {}
 
  ngOnInit() {
    this.profileId = this.route.snapshot.paramMap.get('id')!;
  }
}

5. Query Parameters

Query parameters are passed as key-value pairs in the URL (e.g., /profile?id=123). They are not part of the route path but can be accessed using ActivatedRoute.

Example:

// app-routing.module.ts
const routes: Routes = [
  { path: 'profile', component: ProfileComponent }
];
// profile.component.ts
import { ActivatedRoute } from '@angular/router';
 
@Component({
  selector: 'app-profile',
  template: `<h2>Profile Name: {{ name }}</h2>`
})
export class ProfileComponent implements OnInit {
  name: string;
 
  constructor(private route: ActivatedRoute) {}
 
  ngOnInit() {
    this.route.queryParams.subscribe(params => {
      this.name = params['name'] || 'Guest';
    });
  }
}

6. Route Guards

Route guards are used to control access to routes. They can prevent navigation based on specific conditions, such as authentication.

Example:

// auth.guard.ts
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';
 
@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private router: Router) {}
 
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    const isLoggedIn = localStorage.getItem('isLoggedIn');
    if (isLoggedIn) {
      return true;
    } else {
      this.router.navigate(['/login']);
      return false;
    }
  }
}
// app-routing.module.ts
const routes: Routes = [
  { path: 'profile', component: ProfileComponent, canActivate: [AuthGuard] }  // Protect this route
];

7. Route Resolvers

Route resolvers allow pre-fetching data before the route is activated. They can retrieve data before navigating to a route.

Example:

// data.resolver.ts
import { Injectable } from '@angular/core';
import { Resolve } from '@angular/router';
import { Observable } from 'rxjs';
import { DataService } from './data.service';
 
@Injectable({
  providedIn: 'root'
})
export class DataResolver implements Resolve<any> {
  constructor(private dataService: DataService) {}
 
  resolve(): Observable<any> {
    return this.dataService.getData();  // Fetch data before the route is activated
  }
}
// app-routing.module.ts
const routes: Routes = [
  { path: 'profile', component: ProfileComponent, resolve: { data: DataResolver } }
];

The routerLink directive is used to bind an anchor tag to a route, replacing the href attribute. It helps navigate without reloading the page.

Example:

<a routerLink="/about">Go to About</a> <!-- Link that navigates to the About route -->

9. Auxiliary Routes

Auxiliary routes allow you to display multiple components at the same time in different outlets. You can have a primary and secondary outlet.

Example:

// app-routing.module.ts
const routes: Routes = [
  { path: 'primary', component: PrimaryComponent, outlet: 'primary' },
  { path: 'secondary', component: SecondaryComponent, outlet: 'secondary' }
];
<!-- app.component.html -->
<router-outlet name="primary"></router-outlet>  <!-- Primary outlet -->
<router-outlet name="secondary"></router-outlet>  <!-- Secondary outlet -->
 
<!-- Navigation for auxiliary routes -->
<a [routerLink]="[{ outlets: { primary: ['primary'], secondary: ['secondary'] } }]">Go to Auxiliary Routes</a>

10. Primary and Secondary Router Outlets

Angular supports multiple router outlets, allowing you to display different views in various parts of the UI. The primary router outlet is used by default, while secondary outlets can be used for additional content.

Example:

<!-- app.component.html -->
<router-outlet></router-outlet>  <!-- Default primary outlet -->
<router-outlet name="secondary"></router-outlet>  <!-- Secondary outlet for auxiliary routes -->

Summary of Angular Routing Features:

  1. Component Route and Path: Define paths and associate them with components.
  2. Router Outlet: Placeholder to render components.
  3. Route Matching Strategies: Controls how routes are matched.
  4. Route Parameters: Dynamic values in the URL for dynamic content.
  5. Query Parameters: Optional parameters in the URL to pass data.
  6. Route Guards: Protect routes based on conditions (e.g., authentication).
  7. Route Resolvers: Pre-fetch data before navigating to a route.
  8. RouteLink Directive: Use routerLink to navigate without a page reload.
  9. Auxiliary Routes: Render multiple views in different sections of the UI.
  10. Primary and Secondary Router Outlets: Support for multiple outlets to handle complex layouts.

These features of Angular’s routing system provide flexibility and control for creating dynamic and user-friendly single-page applications (SPA).