0
0
Angularframework~30 mins

Module lazy loading preview in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
Module lazy loading preview
📖 Scenario: You are building a simple Angular app that has two feature modules: AdminModule and UserModule. To improve performance, you want to load these modules only when the user navigates to their routes.This technique is called lazy loading. It helps the app start faster by loading only the necessary code first.
🎯 Goal: Create an Angular app routing setup that lazy loads AdminModule and UserModule when the user visits /admin and /user paths respectively.
📋 What You'll Learn
Create a routes array with lazy loading configuration
Use the loadChildren property with dynamic import syntax
Set up routes for /admin and /user paths
Export the routing configuration as AppRoutingModule
💡 Why This Matters
🌍 Real World
Lazy loading modules is a common technique in Angular apps to improve startup speed and user experience by loading code only when needed.
💼 Career
Understanding lazy loading is important for Angular developers to build scalable and performant applications.
Progress0 / 4 steps
1
Create the routes array with lazy loading paths
Create a constant called routes that is an array with two objects. The first object should have path set to 'admin' and loadChildren set to a function that imports './admin/admin.module' and returns AdminModule. The second object should have path set to 'user' and loadChildren set to a function that imports './user/user.module' and returns UserModule.
Angular
Need a hint?

Use the dynamic import syntax import('path').then(m => m.ModuleName) inside loadChildren.

2
Import RouterModule and NgModule, then configure RouterModule
Import RouterModule from '@angular/router' and NgModule from '@angular/core' respectively. Then create an Angular module class called AppRoutingModule decorated with @NgModule. Inside the decorator, add imports with RouterModule.forRoot(routes) and exports with RouterModule.
Angular
Need a hint?

Remember to import NgModule from @angular/core and RouterModule from @angular/router.

3
Add a default route redirecting to /user
Add a new object at the start of the routes array with path set to an empty string '' and redirectTo set to 'user'. Also add pathMatch set to 'full'.
Angular
Need a hint?

The default route uses redirectTo and pathMatch: 'full' to redirect empty path to /user.

4
Add a wildcard route to redirect unknown paths to /user
Add a new object at the end of the routes array with path set to '**' and redirectTo set to 'user'. This will catch all unknown routes and redirect them to the user module.
Angular
Need a hint?

The wildcard route uses path: '**' to catch all unknown URLs and redirect them.