• Skip to primary navigation
  • Skip to main content
  • Skip to footer

Codemotion Magazine

We code the future. Together

  • Discover
    • Events
    • Community
    • Partners
    • Become a partner
    • Hackathons
  • Magazine
    • Backend
    • Frontend
    • AI/ML
    • DevOps
    • Dev Life
    • Soft Skills
    • Infographics
  • Talent
    • Discover Talent
    • Jobs
    • Manifesto
  • Companies
  • For Business
    • EN
    • IT
    • ES
  • Sign in
ads

Davide PassafaroApril 24, 2024

Redirecting Guards and Resolvers in Angular v18

Frontend
guards and resolvers angular 18
facebooktwitterlinkedinreddit

In the modern era of web development, creating dynamic and interactive applications has become the norm. Implementing features that are exclusive to certain users, or available under specific conditions, can be a very complex challenge.

For this reason, Angular offers a routing system based on Routes, rules, and components, enabling you to easily design your applications.

Recommended article
May 26, 2025

10 React expert tips that will change your life!

Lucilla Tomassi

Lucilla Tomassi

Frontend

In this article, I will discuss safeguarding Routes redirecting the user elsewhere, using also a new feature introduced in Angular v18.

But before we proceed, let’s have a brief review of Angular Router…


Angular Router Guards and Resolvers

Angular Router library allows you to manage navigation within your Angular application, defining a list of Routes.

Each Route is defined by a series of information, such as the path to access it, the Angular component to load, child Routes, and much more:

import { Route } from '@angular/router';
import { MyFeatureComponent, MyFeatureGuard } from './my-feature';

const routes: Route[] = [
  {
    path: 'my-feature',
    component: MyFeatureComponent,
    canActivate: [MyFeatureGuard],
    data: {
      id: "my-feature-id"
    }
  }
];
Code language: TypeScript (typescript)

You can protect one or more Routes, restricting the access or the exit, based on certain conditions, using functions called Guards:

import { Route } from '@angular/router';
import { MyService } from './my-feature';

const myRoute: Route = [
  path: 'my-feature',
  canMatch: [() => inject(MyService).canMatch()],
  canActivate: [() => inject(MyService).canActivate()],
  canActivateChild: [() => inject(MyService).canActivateChild()],
  canDeactivate: [() => inject(MyService).canDeactivate()],
];
Code language: TypeScript (typescript)

There are four types of Angular Guards, each with a different role:

  • canMatch: used to verify that a Route can be loaded. You can define multiple Routes for a single path and use this guard to select only one based on certain conditions;
  • canActivate: used to determine whether a user can activate a particular Route. For example, you can use it to control access to pages reserved only for certain users;
  • canActivateChild: similar to canActivate, but it controls also the access to child Routes of a main Route. It runs on every navigation towards a child Route, even if it started from another child Route;
  • canDeactivate: used to verify whether a user can exit a given Route. For example, you can use it to ask for confirmation before leaving a page.

Note: originally, Guards were implemented as Injectable services. Following the introduction of the inject() function, it was possible to define them as functions. As a result, Injectable Guards are currently deprecated.

Order of execution of the Guards during navigation

Furthermore, you can use Resolver functions to prepare data for a Route:

import { Route } from '@angular/router';
import { MyService } from './my-feature';

const myRoute: Route = [
  path: 'my-feature',
  resolve: {
    user: () => inject(MyService).getUserInfo(),
    config: () => inject(MyService).getUserConfig()
  }
];
Code language: TypeScript (typescript)

Using Resolvers is a great approach to ensure the presence of data before accessing a Route, avoiding dealing with missing data in a page.

Order of execution of Resolvers during navigation

Now that I covered the basics, let’s see how to protect your Routes by redirecting users elsewhere.

Use Guards and Resolvers to redirect navigation

Angular Guards allow you to prevent access or exit to one or more Routes, blocking navigation.

However, to ensure a smoother user experience, it is often preferable to redirect the user to another Route.

Thanks to Guards, we can achieve this very easily, starting a new navigation before blocking the current one:

import { inject } from '@angular/core';
import { Route, Router } from '@angular/router';
import { MyPage } from './pages/my-page';

const route: Route = {
  path: 'my-page',
  component: MyPage,
  canActivate: [
    () => {
      const router = inject(Router);
      router.navigate(['./my-other-page']);
      return false;
    },
  ],
};
Code language: TypeScript (typescript)

You can achieve a similar result using the Resolvers, starting a new navigation inside them:

import { Route, Router } from '@angular/router';
import { MyService } from './my-feature';

const myRoute: Route = [
  path: 'my-feature',
  resolve: {
    user: () => {
      const router = inject(Router);
      router.navigate(['./my-other-page']);
      return null;
    }
  }
];
Code language: TypeScript (typescript)

Redirect with UrlTree

Alternatively, you can redirect navigation by having Guards and Resolvers return a UrlTree representing the new Route:

import { inject } from '@angular/core';
import { Route, Router, UrlTree } from '@angular/router';
import { MyPage } from './pages/my-page';

const route: Route = {
  path: 'my-page',
  component: MyPage,
  canActivate: [
    () => {
      const router: Router = inject(Router);
      const urlTree: UrlTree = router.parseUrl('./my-other-page');
      return urlTree;
    },
  ],
};
Code language: TypeScript (typescript)

However, this technique does not allow you to redirect navigation using NavigationExtras, as allowed by the previous technique:

canActivate: [
  () => {
    const router = inject(Router);
    router.navigate(['./my-other-page'], { skipLocationChange: true });
    return false;
  }
]
Code language: TypeScript (typescript)

Redirect with RedirectCommand

To overcome this, Angular v18 introduces a new RedirectCommand class capable of handling NavigationExtras, enabling you to redirect navigation in Guards and Resolvers:

import { inject } from '@angular/core';
import { RedirectCommand, Route, Router, UrlTree } from '@angular/router';
import { MyPage } from './pages/my-page';

const route: Route = {
  path: 'my-page',
  component: MyPage,
  canActivate: [
    () => {
      const router: Router = inject(Router);
      const urlTree: UrlTree = router.parseUrl('./my-other-page');
      return new RedirectCommand(urlTree, { skipLocationChange: true });
    },
  ],
};
Code language: TypeScript (typescript)

The introduction of this new RedirectCommand class ensures great maintainability for Guards and Resolvers.

Having been designed specifically for these use cases, it can be easily extended to adapt to any necessary new parameters in the future.


Thanks for reading so far 🙏

I’d like to have your feedback so please feel free to contact me for any. 👏

Then, if you really liked it, share it among your community, tech bros and whoever you want. 👋😁

Related Posts

Native CSS: A Whole New Story – Part 1

Daniele Carta
March 3, 2025

Understanding Angular — Exploring Dependency Injection and Design Patterns — Part 0 🔥🚀

Giorgio Galassi
February 5, 2025

Let’s Create a Bento Box Design Layout Using Modern CSS

Massimo Avvisati
January 21, 2025
React library: all you need to know about it.

Building reusable multiple-step form in ReactJS

Noa Shtang
August 8, 2024
Share on:facebooktwitterlinkedinreddit

Tagged as:Angular v18 guards and resolvers

Davide Passafaro
My name is Davide Passafaro and I am Senior Frontend Engineer at Awork. I lead two developer communities in Rome, GDG Roma Città and Angular Rome, and actively contribute to the tech community as a writer and speaker. When i shut down my computer I like to play board games and archery, not both together till now. I also like escape rooms and memes.
Is Devin Fake? The Dev Community Is Taking a Closer Look
Previous Post
Supply Chain Threats 101
Next Post

Footer

Discover

  • Events
  • Community
  • Partners
  • Become a partner
  • Hackathons

Magazine

  • Tech articles

Talent

  • Discover talent
  • Jobs

Companies

  • Discover companies

For Business

  • Codemotion for companies

About

  • About us
  • Become a contributor
  • Work with us
  • Contact us

Follow Us

© Copyright Codemotion srl Via Marsala, 29/H, 00185 Roma P.IVA 12392791005 | Privacy policy | Terms and conditions