Angular Router In Depth
Tags: angular, webdev, javascript
Published: 2023-04-19 14:53:45

Angular Router is a powerful feature that allows you to handle navigation in your Angular application. It enables you to navigate between different components and views within your application, and handle user interactions such as clicking on links or submitting forms. In this discussion, we will dive into the details of Angular Router, explore its features, and provide examples of how to use it in your application.

Angular Router Configuration:

To use Angular Router in your application, you need to configure it by setting up routes. Routes define the URL paths and associated components for your application. You can configure routes in the app-routing.module.ts file, which is automatically created when you generate a new Angular project using the Angular CLI.

Here is an example of configuring routes in Angular:

```
import { NgModule } from '@angular/core';
import { Routes, RouterModule } 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 { }

```

In the code above, we have defined two routes: the home route, which is the default route that displays the HomeComponent, and the about route, which displays the AboutComponent. We have also imported the RouterModule and configured the routes using the forRoot method.

Navigation in Angular:

Once you have configured your routes, you can use the Angular Router to handle navigation in your application. Navigation can be triggered by clicking on links, submitting forms, or programmatically using the Router API.

Here is an example of how to create a link that navigates to the AboutComponent:

```
<a routerLink="/about">About Us</a>

```

In the code above, we have used the routerLink directive to create a link that navigates to the about route. The routerLink directive automatically generates the correct URL based on the route configuration in the app-routing.module.ts file.

You can also handle navigation programmatically using the Router API. Here is an example of how to navigate to the AboutComponent programmatically:

```
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-home',
  template: `
    <button (click)="navigateToAbout()">Go to About Us</button>
  `,
  styles: []
})
export class HomeComponent implements OnInit {

  constructor(private router: Router) { }

  ngOnInit() {
  }

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

}

```

In the code above, we have imported the Router and injected it into the HomeComponent. We have also created a button that triggers the navigateToAbout method when clicked. The navigateToAbout method calls the Router's navigate method to navigate to the about route.

Route Parameters:

Route parameters allow you to pass data between components when navigating. Route parameters are defined using a colon followed by the parameter name in the route path.

Here is an example of how to define a route with a parameter:

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

```

In the code above, we have defined a route with a parameter named id.

Here is an example of how to navigate to the AboutComponent with a parameter:

```
<a [routerLink]="['/about', 123]">About Us</a>

```

In the code above, we have used the routerLink directive to create a link that navigates to the about route with the id parameter set to 123.

Here is an example of how to access the parameter in the AboutComponent:

```
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-about',
  template: `
    <h1>About Us</h1>
    <p>ID: {{id}}</p>
  `,
  styles: []
})
export class AboutComponent implements OnInit {
  id: number;

  constructor(private route: ActivatedRoute) { }

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

}

```

In the code above, we have imported the ActivatedRoute and injected it into the AboutComponent. We have also subscribed to the params Observable to get the value of the id parameter from the route.

Guarding Routes:

You can also use guards to protect routes and prevent unauthorized access. Guards are functions that are executed before navigation to determine if the user is allowed to access the route. There are several types of guards in Angular, including CanActivate, CanActivateChild, CanDeactivate, and Resolve.

Here is an example of how to use the CanActivate guard to protect a route:

```
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    return this.authService.isLoggedIn();
  }

}

```

In the code above, we have created an AuthGuard that implements the CanActivate interface. The AuthGuard checks if the user is logged in by calling the isLoggedIn method of the AuthService. If the user is logged in, the guard allows navigation to the route. If the user is not logged in, the guard redirects the user to the login page.

To use the AuthGuard, you need to add it to the route configuration:

```
const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'about/:id', component: AboutComponent, canActivate: [AuthGuard] }
];

```
In the code above, we have added the AuthGuard to the about route.

Conclusion:

In this discussion, we have explored the features of Angular Router and provided examples of how to use it in your application. We have discussed how to configure routes, handle navigation, pass data between components using route parameters, and protect routes using guards. Angular Router is a powerful feature that enables you to create complex navigation and user interaction in your Angular application.