Boost Angular App Speed Using the Defer Feature
Angular's defer feature is a game-changer for performance. Learn how it works and how to implement it to speed up your apps significantly. Download full source code.
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.
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.
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’
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’
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');
});
});
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();
});
});
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;
}
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>
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}
];
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>
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>
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.
Angular's defer feature is a game-changer for performance. Learn how it works and how to implement it to speed up your apps significantly. Download full source code.
Explore how Zone.js powers change detection in Angular apps. This comprehensive guide covers how it works, use cases, performance tips, and advanced debugging.
Learn how to build modern full stack applications using Angular and ASP.NET Core. Explore architecture, API integration, deployment tips, and best practices.
Learn how to implement Azure AD authentication in your Angular app using MSAL and connect it securely with ASP.NET Core Web API. Step-by-step setup included.
Boost your Angular projects with these top development best practices. Learn tips for performance, maintainability, code quality, and scalable architecture.
Dive into Angular 20's latest updates, trending features, performance boosts, and tools reshaping frontend development. All in one detailed, easy-to-read guide.
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.