Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Routing with Angular

Angular is a robust framework for building web applications and offers a feature-rich router. The router allows for client-side navigation within a single-page application, making it possible to load different parts of an app without requiring a full page reload.

Different Routing Approaches in Angular

Now, we will discuss two specific routing strategies within Angular: PathLocationStrategy and HashLocationStrategy.

1. PathLocationStrategy in Detail

PathLocationStrategy is the default Angular routing strategy, and it uses the browser's history API to create clean, human-readable URLs.

Here's how it functions and its benefits:

  • Clean URLs: This strategy results in URLs that do not have a hash (#) part. They look and feel like the URLs for a traditional website. For example, navigating a user profile page might result in a URL like http://www.example.com/user/johndoe.
  • Server Configuration: To use PathLocationStrategy, the server must be properly configured to return the application's host page (usually index.html) when it receives a request for a deep link URL. This is necessary because, without the correct server-side configuration, a user refreshing the page or entering a URL directly into the browser could receive a 404 error since the server doesn't have a matching file.
  • HTML5 Support: It relies on the HTML5 History API, which allows for manipulation of the browser's history, enabling navigation back and forth without full page reloads.

2. HashLocationStrategy in Detail

HashLocationStrategy is an alternative routing method in Angular that uses URL hash fragments for client-side navigation.

Here's a breakdown of its functionality and use cases:

  • Hash Fragments: This strategy adds a hash (#) to the URLs. When using HashLocationStrategy, the URL will look like http://www.example.com/#/user/johndoe. The part of the URL after the # symbol is not sent to the server, which is why the application can use it for client-side routing.
  • No Server Configuration Required: Since the server does not process everything after the hash, this strategy does not require any special server-side configuration. It's particularly useful if you cannot ensure the server always returns the application page for all deep link URLs.
  • Legacy Browser Support: It is also a good fallback for older browsers that do not support the HTML5 History API, ensuring that routing functionalities work across various browsers and environments.

Unlike React and Vue, Angular comes with its own routing functionality built into the core framework, so no additional package installation is necessary.

Setting Up

Setting up routing in an Angular application usually starts when you create a new Angular project. During the project creation process using Angular CLI, you can opt to include routing.

To create a new Angular project with routing, you can use the following Angular CLI command:

ng new my-app --routing

After creating the project, you will find a RouterModule imported into your AppModule.

Basic Usage

Angular uses a configuration approach to define routes. Routes are declared in an array of objects and then passed as an argument to RouterModule.forRoot().

Here is an example to demonstrate basic routing in Angular:

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 { }

In the above code example:

  • RouterModule.forRoot(routes): The routes are registered with Angular's dependency injection system.
  • Routes: An array of route objects that maps a path to a component.

You can then use Angular's <router-outlet> directive and the routerLink attribute for displaying and linking routes:

<a [routerLink]="['/']">Home</a>
<a [routerLink]="['/about']">About</a>
<router-outlet></router-outlet>

Advanced Features

Route Parameters

You can include variable parts in your URL paths by using route parameters:

{ path: 'user/:id', component: UserComponent }

In the UserComponent, you can access the ID with Angular's ActivatedRoute service.

Child Routes

Angular allows you to nest routes, providing the capability to create complex UIs with nested views.

{
    path: 'users',
    component: UsersComponent,
    children: [
      { path: ':id', component: UserDetailComponent },
      { path: '', component: UserListComponent }
    ]
  }

Route Guards

Angular provides route guards like CanActivate, CanDeactivate, and others that allow you to add complex logic around route transitions.

{ path: 'admin', component: AdminComponent, canActivate: [AuthGuard] }

Angular provides a powerful in-built library for routing. You can find everything you need to know about routing in Angular applications on the official documentation page.