DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

5

Angular v18 route's redirectTo property can be a function

In šŸ…°ļø Angular v18, a route's redirectTo property can be a function that returns a string or UrlTree.

We can create more dynamic redirects based on the application's state:

const routes: Routes = [
  { path: "first-component", component: FirstComponent },
  {
    path: "old-user-page",
    redirectTo: ({ queryParams }) => {
      const errorHandler = inject(ErrorHandler);
      const userIdParam = queryParams['userId'];
      if (userIdParam !== undefined) {
        return `/user/${userIdParam}`;
      } else {
        errorHandler.handleError(new Error('Attempted navigation to user page without user ID.'));
        return `/not-found`;
      }
    },
  },
  { path: "user/:userId", component: OtherComponent },
];
Enter fullscreen mode Exit fullscreen mode

Check it out šŸ‘‰ https://angular.dev/guide/routing/common-router-tasks#setting-up-redirects


I hope you found it helpful. Thanks for reading. šŸ™

Let's get connected! You can find me on:

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (1)

Collapse
 
jangelodev profile image
JoĆ£o Angelo ā€¢

Hi Nhan Nguyen,
Top, very nice !
Thanks for sharing

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

šŸ‘‹ Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay