Codecademy Logo

Angular Routing and Navigation

Angular Router

In Angular, the Router is a singleton service that handles navigation between different views within a single-page application. It manages the application’s route configurations and coordinates navigation to display the correct components based on the URL path.

Having one instance of the Router service in an application allows it to maintain its state across different parts, preserving navigation history and ensuring consistent route information.

Angular Route Configuration

Angular routes are defined in a Routes typed array, where each route maps a URL path to a specific component. The corresponding component is displayed when a user navigates to a particular path.

Angular checks the routes from top to bottom, making ordering the routes important. More specific routes should be listed before less specific ones to ensure the correct component is activated for a given URL.

export const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'users', component: UserListComponent },
{ path: 'users/:id', component: UserDetailComponent },
{ path: '**', component: PageNotFoundComponent },
];

Angular Declarative Navigation

The RouterLink directive in Angular templates allows declarative navigation between routes without a full page reload. It works like an HTML anchor tag but with the routerLink attribute applied. The directive keeps the app within the single-page application architecture.

<!-- Basic static navigation -->
<a routerLink="/books">Books</a>
<!-- Property-bound routerLink (dynamic navigation) -->
<a [routerLink]="['/books', bookId]">Book {{ bookId }}</a>
<!-- routerLink with query parameters -->
<a [routerLink]="['/books']" [queryParams]="{ filter: 'available' }">Available Books</a>
<!-- routerLink with both path and query parameters -->
<a [routerLink]="['/category', categoryId]" [queryParams]="{ sort: 'newest' }">Category {{ categoryId }}</a>

Angular Programmatic Navigation

Angular’s Router service provides the navigate() method for programmatic navigation, allowing route changes based on logic or user actions (e.g., after form submission).

// Basic programmatic navigation to a static path
this.router.navigate(['/books']);
// Programmatic navigation with a path parameter
this.router.navigate(['/books', bookId]);
// Programmatic navigation with a query parameter
this.router.navigate(['/books'], { queryParams: { filter: 'available' } });
// Programmatic navigation with a path and query parameter
this.router.navigate(['/category', categoryId], { queryParams: { sort: 'newest' } });
// Chaining actions after navigation
this.router.navigate(['/books', bookId]).then(() => {
console.log('Navigation to book completed!');
});

Angular Routes Array

A Routes array contains route definitions that specify paths and their associated components. This array informs Angular which component to load when a user navigates to a particular path.

export const routes: Routes = [
{ path: 'books', component: BooksComponent },
];

Angular Dynamic Route Parameters

Dynamic route parameters in Angular are defined using a colon (:) in the route’s path. These parameters allow flexibility, such as passing an id to load different content based on the route.

{ path: 'books/:id', component: BookDetailComponent } //example URL: example.com/books/123

Angular Nested Routes

Angular’s routing system allows for the hierarchical organization of routes through nested routing. This is implemented using a children array within a parent route definition. Nested routes allow multiple components to display within a parent component’s view.

{
path: 'books/:id',
component: BookDetailComponent,
children: [
{ path: 'reviews', component: ReviewsComponent },
{ path: 'author', component: AuthorComponent },
]
}

Angular RouterOutlet

The RouterOutlet directive in Angular specifies where routed components should be displayed in the template.

In the template, it is represented by the <router-outlet> HTML element.

<!-- app.component.html -->
<nav>
<a routerLink="/home">Home</a>
<a routerLink="/about">About</a>
<a routerLink="/contact">Contact</a>
</nav>
<!-- Routed components are displayed here -->
<router-outlet></router-outlet>

Angular Route Redirection

The redirectTo attribute in Angular routes allows for automatic redirection from one path to another. You can also use pathMatch to control how the redirection occurs (e.g., matching the full URL or part of it).

// Redirection will match `/old-users` but not `/old-users/123`
{ path: 'old-users', redirectTo: '/users', pathMatch: 'full' }

Angular Wildcard Routes

Wildcard routes (**) in Angular handle 404 errors or unmatched URLs by displaying a specific component, such as a “Page Not Found” view, when no valid routes match the request.

The wildcard route is typically defined at the bottom of a routes array because it should match any URL and be triggered last.

const routes: Routes = [
{ path: 'first-component', component: FirstComponent },
{ path: 'second-component', component: SecondComponent },
// ... other specific routes ...
{ path: '**', component: PageNotFoundComponent } // Wildcard route
];

Angular Component Input Binding

The withComponentInputBinding() function in Angular allows route parameters and query parameters to be automatically bound to component inputs using the @Input decorator, simplifying data access within the component.

//app.config.ts
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes, withComponentInputBinding())]
};
//app.routes.ts
export const routes: Routes = [
{ path: 'product/:id', component: ProductDetailComponent },
];
//product-detail.component.ts
@Component({ ... })
export class ProductDetailComponent {
@Input() id = '';
}

Angular Location Service

The Location service in Angular allows manipulation of the browser’s URL without reloading the entire page. The Location service is part of Angular’s @angular/common package and needs to be imported and injected into a component to use its methods.

// Import Location from Angular's common module
import { Location } from '@angular/common';
import { Component, inject } from '@angular/core';
@Component({...})
export class ExampleComponent {
// Inject the Location service into the component
private location = inject(Location);
}

Angular History Navigation

Angular’s Location service offers back() and forward() methods for navigating through the browser’s history programmatically, giving more control over navigation rather than relying on browser functionality.

// Import Location from Angular's common module
import { Location } from '@angular/common';
import { Component, inject } from '@angular/core';
@Component({...})
export class ExampleComponent {
// Inject the Location service into the component
private location = inject(Location);
// Navigate back in browser history
goBack() {
this.location.back();
}
// Navigate forward in browser history
goForward() {
this.location.forward();
}
}

Angular Navigation Promise

The navigate() method in Angular returns a promise that resolves when navigation is complete. This allows for actions to be taken after navigation, such as showing alerts or updating the state.

this.router.navigate(['/home']).then(() => {
alert('Navigation completed');
});

Learn more on Codecademy