Table of Contents


Function Based Redirect Routes

When working with modern Angular applications in an Nx monorepo setup, implementing function-based redirect routes offers a powerful way to manage dynamic navigation. These routes enable redirection logic to be defined within a function, allowing decisions to be made based on real-time conditions like user roles, authentication status, or app state. In this blog, we’ll explore how this flexible routing strategy is implemented in the app-two project of an Nx CLI workspace.

Before diving into the implementation, it's essential to ensure your development environment is properly configured. You should be using Node.js v20.1.0 or later (minimum required is 16.9.0) to take advantage of the latest JavaScript capabilities and performance enhancements. Additionally, make sure Angular CLI v19.2.10 or later is installed to maintain compatibility with the latest Angular and Nx routing features. With the right setup, you’ll be ready to harness the full potential of function-based redirects in your Angular applications.

Function based routes redirect function implementation is done in the nx cli workspace’s project app-two.

Prerequisites

To follow along, ensure you have:

Node.js V20.1.0 (should be greater than 16.9.0)

Angular CLI v19.2.10 (or later)

Once Node.js and Angular is installed, you can proceed to install the Nx cli

Let’s start by creating a new angular application, the workspace.

Step 1: Create a new angular application

To create an angular application in nx workspace run the command, the name if the application is app-two


Run ‘nx g @nx/angular:application apps/app-two’						
						

Step 2: Create components in angular application

Create the components for the home page, user list page, sales-person list and an error page. Commands are mentioned below


Run ‘nx g @nx/angular:component apps/app-two/src/app/home/home’
Run ‘nx g @nx/angular:component apps/app-two/src/app/user-list/user-list’
Run ‘nx g @nx/angular:component apps/app-two/src/app/sales-person-list/sales-person-list’
Run ‘nx g @nx/angular:component apps/app-two/src/app/error/error’						
						

Step 3: App Component

In app.component.html remove welcome component selector and add router-outlet


<router-outlet></router-outlet>
							

In app.component.ts remove NxWelcomeComponent from imports


@Component({
  imports: [RouterModule],
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrl: './app.component.css',
})
							

In app.component.spec.ts change the test code for test the component


import { TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { RouterModule } from '@angular/router';


describe('AppComponent', () => {
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [AppComponent, RouterModule.forRoot([])],
    }).compileComponents();
  });


  it(`should have as title 'app-two'`, () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app.title).toEqual('app-two');
  });
});
							
							

Step 4: Creating home page

For creating the home page do these changes in following files of the home component.

Do the changes in home.component.html, first remove home works and added two links with for users list and sales manager list


<div class="parent">
    <div class="container">
        <div class="d-flex">
            <div class="box">
                <a routerLink="/list/user">
                    <img src="assets/1.png" alt="">
                    <h5>Users</h5>
                </a>
            </div>
            <div class="box">
                <a routerLink="/list/sales">
                    <img src="assets/2.webp" alt="">
                    <h5>Sales Manager</h5>
                </a>
            </div>
        </div>
    </div>
</div>						
						

For this you have to add two images in the public directory of app-two project. Create assets folder and add two images with names 1.png and 2.webp and mention them in the html file.

In home.component.ts add RouterLink to imports to be used in the html file.


import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterLink } from '@angular/router';
@Component({
  selector: 'app-home',
  imports: [CommonModule, RouterLink],
  templateUrl: './home.component.html',
  styleUrl: './home.component.css',
})
export class HomeComponent {}
						

In home.component.css add styling for user list page and sales person page links.


.box{
    width: 15%;
    float: left;
    text-align: center;
    height: auto;
    padding: 20px;
    background-color:white
}
.box img{
    width: 100%;
}
.box a{
    text-decoration: none;
    color: black;
}						
						

In home.component.spec.ts change the test code to run test command


import { ComponentFixture, TestBed } from '@angular/core/testing';
import { HomeComponent } from './home.component';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { of } from 'rxjs';
describe('HomeComponent', () => {
  let component: HomeComponent;
  let fixture: ComponentFixture<HomeComponent>


  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [HomeComponent, RouterLink],
      providers: [
        {
          provide: ActivatedRoute,
          useValue: {
            params: of({}),
            queryParams: of({}),
            snapshot: {
              data: {},
              params: {},
              queryParams: {}
            }
          }
        }
      ]
    }).compileComponents();


    fixture = TestBed.createComponent(HomeComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
	});


  it('should create', () => {
    expect(component).toBeTruthy();
  });
});
						

Step 5: Add Styling in styles.css

Add these classes in styles.css to apply on all components .


*{
    box-sizing: border-box;
    font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
}
.parent{
    padding: 30px 0;
}
.container{
    margin: 0 auto;
    max-width: 87%;
}
.d-flex{
    display: flex;
}
.justify-content-between{
    justify-content: space-between;
}
.text-center{
    text-align: center;
}						
						

Step 6: Add Error Component

In error.component.html remove error works and add the heading for Page Not Found


<div class="parent">
    <h1 class="text-center">Page Not Found</h1>
</div>						
						

Step 7: Add Routes for home page, user list, salesperson data

Create routes in app.routes.ts for home, user list and salesperson list and a redirect function with path list which redirects based on params


import { Route } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { UserListComponent } from './user-list/user-list.component';
import { SalesPersonListComponent } from './sales-person-list/sales-person-list.component';
import { ErrorComponent } from './error/error.component';


export const appRoutes: Route[] = [
    {path:"", redirectTo:'/home', pathMatch:'full'},
    {path:"home", component:HomeComponent},
    {path:"list/:id", redirectTo:(data)=>{
        if(data.params['id'] == 'sales') return 'salesPersonData'
        else if(data.params['id'] == 'user') return 'usersData'
        else return "**"
    }, pathMatch:'full'},
    {path:"usersData", component:UserListComponent},
    {path:"salesPersonData", component:SalesPersonListComponent},
    {path:"**", component:ErrorComponent}
];
	
						

Step 8: UserList Page

Add a heading tag for User’s Data to html file user-list.component.html


<div class="parent">
    <div class="container">
        <div class="heading d-flex justify-content-between">
            <h2>User's Data</h2>
        </div>
    </div>
</div>					
						

Step 9: Sales Person List Page

Add a heading tag for Sales Person Data to html file sales-person-list.component.html


<div class="parent">
    <div class="container">
        <div class="heading d-flex justify-content-between">
            <h2>Sales Person Data</h2>
        </div>
    </div>
</div>						
						

Conclusion

The RedirectTo property in route configuration in Angular 19 receives AngularRouteSnapshot as a parameter allowing us dynamically determine the redirect destination based on route parameters, query parameters or other factors. To create flexible and complex redirect logic based on runtime conditions. Better readability by moving the redirect logic inside the route.

Latest from Prishusoft

Ready to Build Something Amazing?

Get in touch with Prishusoft – your trusted partner for custom software development. Whether you need a powerful web application or a sleek mobile app, our expert team is here to turn your ideas into reality.

image