In the dynamic world of web development, creating seamless user experiences often involves navigating through various sections of a single-page application (SPA) without full page reloads. Angular, with its powerful routing and navigation features, enables developers to achieve just that. In this article, we will learn about Angular’s routing and navigation capabilities, guiding you through the setup of routes, handling route parameters and harnessing the power of lazy loading modules. By the end of this article, you’ll be equipped to create engaging SPAs that provide smooth and intuitive user journeys.
Prerequisites:
Before we begin, ensure that you have Angular CLI installed on your system. If not, you can install it using the following command:
npm install -g @angular/cli
Create a New Angular Project
If you don’t already have an Angular project, you can create one using the Angular CLI:
ng new coding-charcha-angular-routing-demo
Navigate to the project directory and then
Install and Configure the Angular Router
Angular Router is a separate module that needs to be installed and configured. Install it using the following command:
ng add @angular/router
Create Components
From CLI use the following command to generate two components Home and About
ng generate component home
ng generate component about
Define Your Routes
Open the app.module.ts
file located in the src/app
directory. Import the RouterModule
and define your routes using the RouterModule.forRoot()
method. Each route object consists of a path
and the corresponding component to render:
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
// Define other routes here
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppModule { }
Add Router Outlet
In your main application template (usually app.component.html
), add a <router-outlet></router-outlet>
element. This placeholder will be used to render the components associated with the defined routes:
<nav>
<a routerLink="/">Home</a>
<a routerLink="/about">About</a>
<!-- Add more navigation links -->
</nav>
<router-outlet></router-outlet>
Test Application
ng serve
Open your browser and navigate to http://localhost:4200
. You should now see the home component rendered by default.
Click on the navigation links to see the corresponding components being displayed within the <router-outlet>
.
Handling Route Parameters:
What Are Router Parameters?
Router parameters are values passed as part of a URL to provide context and data to a specific route. This enables dynamic content rendering and enhances user interactions within an application.
Lets create two new components Products and ProductDetails by running the following command from the command line
ng generate component products
ng generate component product-detail
Put the products link just under home and about us page under the nav in app.component.html
file
<nav>
<a routerLink="/">Home</a>
<a routerLink="/about">About</a>
<a routerLink="/products">Product</a>
<!-- Add more navigation links -->
</nav>
<router-outlet></router-outlet>
Now under products component put these following lines of code in ‘product.component.html’ as below
<div class="product">
<h4><a routerLink="/product/1">Product 1</a></h4>
<h4><a routerLink="/product/2">Product 2</a></h4>
<h4><a routerLink="/product/3">Product 2</a></h4>
</div>
Configure Routes with Parameters
- In your Angular project, navigate to the
app-routing.module.ts
file (or the module where you’ve defined your routes). - Modify the route configuration to include a parameter by using the
:parameterName
syntax. For example:
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'products', component: ProductsComponent},
{ path: 'product/:id', component: ProductDetailComponent },
// Define other routes
];
Accessing Route Parameters in Components
Import the ActivatedRoute
class from @angular/router
into the component where you want to access the route parameters: . In our case we want to access the route parameter in product details component. So we are going to import ActivatedRoute
in product details component’s product-details.component.ts file
import { ActivatedRoute } from '@angular/router';
Inject ActivatedRoute
into the component’s constructor. In the same file within the constructor put the following code
constructor(private route: ActivatedRoute) { }
Inside the component’s lifecycle hooks (usually ngOnInit
), subscribe to the params
observable provided by ActivatedRoute
. This allows you to retrieve and react to changes in the route parameters:
ngOnInit() {
this.route.params.subscribe(params => {
const id = params['id'];
// Fetch product details based on the 'id'
});
}
Full code for product-details.component.ts is as below
import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.route.params.subscribe(params => {
const productId = params['id'];
// Fetch product details based on the 'id'
});
}
Lazy Loading in Angular
What is Lazy Loading in Angular ?
Lazy loading is a technique in software development where resources, such as code or assets, are loaded only when they are needed, rather than loading them all upfront. In the context of Angular, lazy loading is applied to modules, allowing you to load certain parts of your application on demand, improving initial loading times and overall performance.
Implementation of Lazy Loading in Angular Routes:
Lazy loading is implemented using the loadChildren
property within route configurations. Instead of importing the module directly into the main application module, you specify the path to the module file using the loadChildren
property. Angular will then load that module only when the associated route is accessed.
Here’s an example of how you can set up lazy loading in Angular routes:
Create a Feature Module:
Assume you have a feature that you want to load lazily, such as a “Products” section. First, create a feature module for that section using the Angular CLI:
ng generate module products --route products
This will generate a products
module and configure the route for that module.
Configure Lazy Loading:
In your main routing configuration (usually app-routing.module.ts
), use the loadChildren
property to specify the path to the feature module:
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'products', loadChildren: () => import('./products/products.module').then(m => m.ProductsModule) },
]
Feature Module Routing:
Within the feature module’s routing configuration (in products-routing.module.ts
), define the routes specific to that feature:
const routes: Routes = [
{ path: '', component: ProductsListComponent },
{ path: ':id', component: ProductDetailComponent },
// ... other routes
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class ProductsRoutingModule { }
Use Cases for Lazy Loading in Angular:
- Large Applications: In large applications, loading all modules upfront can lead to longer initial loading times. Lazy loading helps improve the user experience by loading only the necessary modules when they are needed.
- Complex Dashboards: If your application includes complex dashboards or administration sections that not all users will access, lazy loading can be used to load these sections only when required.
- Improving Performance: Lazy loading reduces the initial bundle size, allowing the core functionality of your application to be loaded faster. This is particularly important for improving performance, especially in low-bandwidth or mobile scenarios.
- Code Splitting: Lazy loading supports code splitting, which means that different parts of your application are split into separate bundles. This can help with optimizing browser caching and making subsequent page loads faster.
- Enhancing Developer Experience: Lazy loading can also improve the developer experience, as it isolates modules and reduces the complexity of the main bundle during development, making it easier to manage and test specific parts of the application.
By utilizing lazy loading, you can optimize the performance of your Angular applications by deferring the loading of non-critical modules until they are actually needed. This results in a more responsive and efficient user experience.