Angular Child Routes And Lazy Loading Complete Guide

 Last Update:2025-06-22T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    7 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of Angular Child Routes and Lazy Loading

Explaining Angular Child Routes and Lazy Loading in Detail with Important Information

Child Routes

Child routes are a crucial feature in Angular applications that allow for organizing components in a hierarchical manner. They are used to nest routes within a parent route, providing a structured way to navigate and manage components.

Key Concepts:

  • Parent Component: This is the parent route where the child routes will be nested. It can be visualized as a main navigation element.
  • Outlets: Child components are loaded into a specific <router-outlet> that is defined in the parent component’s template.

Example Structure:

Let's say we have an application with a parent route named "store", and a child route named "products". The path for the child route would be something like store/products.

Router Configuration:

const routes: Routes = [
  {
    path: 'store',
    component: StoreComponent,
    children: [
      {
        path: 'products',
        component: ProductsComponent
      },
      {
        path: 'categories',
        component: CategoriesComponent
      }
    ]
  }
];

In this setup, StoreComponent is the parent component for ProductsComponent and CategoriesComponent.

Lazy Loading

Lazy loading is a technique in Angular that helps to reduce the initial load time of an application by splitting your application into smaller chunks, and loading only the necessary parts when required. This results in a more efficient and snappier user experience.

Key Concepts:

  • Lazy Loaded Modules: A feature module that is loaded on demand using Angular's router.
  • Loader Syntax: Specifies the route that should trigger the lazy loading of a feature module.

Why Use Lazy Loading?

  1. Performance: Reduces the initial bundle size and ensures faster load times for critical pages.
  2. Memory Management: Only loads components as needed, freeing up memory for unused parts of the app.
  3. Optimization: Helps with bandwidth usage, especially in mobile applications.

Setting up Lazy Loading:

To implement lazy loading, you need to use the loadChildren property in your route configuration. This property accepts a function that dynamically imports the module to load.

Example:

Suppose you have a StoreModule that you want to lazily load when the path store is accessed.

const routes: Routes = [
  {
    path: 'store',
    loadChildren: () => import('./store/store.module').then(m => m.StoreModule)
 }
];

In this configuration, when the application navigates to /store, Angular will load the StoreModule and all its child routes.

Important Information

  • Route Guards: Often used in conjunction with routing to manage conditions for when a route can be activated, deactivated, or an asynchronous check is made.
  • Parameterized Routes: Allow dynamic parameter passing in routes, essential for dynamic content loading (e.g., /store/product/:id).
  • Query Parameters and Fragments: Extend routing capabilities by enabling optional data passing and scrolling to specific sections of a webpage respectively (e.g., /store?show=all#products).
  • Preloading Strategy: Offers the flexibility to preload modules in the background to improve performance and responsiveness after initial load.

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement Angular Child Routes and Lazy Loading

Prerequisites:

  • Node.js and npm installed.
  • Angular CLI installed (npm install -g @angular/cli)

Step 1: Create a New Angular Project

Run the following command to create a new Angular project:

ng new angular-child-routes-lazy-loading
cd angular-child-routes-lazy-loading

Step 2: Generate Modules and Components

We'll create a couple of modules (home and about) that we'll load lazily, along with some components.

Generate the HomeModule and components:

ng generate module home --routing
ng generate component home/home
ng generate component home/home-list
ng generate component home/home-detail

Generate the AboutModule and components:

ng generate module about --routing
ng generate component about/about
ng generate component about/about-team
ng generate component about/about-mission

Step 3: Define the Routes for Each Module

First, let's set up the routes for the HomeModule.

src/app/home/home-routing.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { HomeListComponent } from './home-list/home-list.component';
import { HomeDetailComponent } from './home-detail/home-detail.component';

const routes: Routes = [
  {
    path: '',
    component: HomeComponent,
    children: [
      {
        path: 'list',
        component: HomeListComponent,
      },
      {
        path: 'detail',
        component: HomeDetailComponent,
      },
      {
        path: '',
        redirectTo: 'list',
        pathMatch: 'full'
      }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class HomeRoutingModule {}

Next, let's set up the routes for the AboutModule.

src/app/about/about-routing.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AboutComponent } from './about/about.component';
import { AboutTeamComponent } from './about-team/about-team.component';
import { AboutMissionComponent } from './about-mission/about-mission.component';

const routes: Routes = [
  {
    path: '',
    component: AboutComponent,
    children: [
      {
        path: 'team',
        component: AboutTeamComponent,
      },
      {
        path: 'mission',
        component: AboutMissionComponent,
      },
      {
        path: '',
        redirectTo: 'team',
        pathMatch: 'full'
      }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class AboutRoutingModule {}

Step 4: Set Up the Lazy Loading in the Main Routing Module

Now, we'll set up the main application routing module to use lazy loading for the HomeModule and AboutModule.

src/app/app-routing.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LayoutComponent } from './layout/layout.component';

const routes: Routes = [
  {
    path: '',
    component: LayoutComponent,
    children: [
      {
        path: 'home',
        loadChildren: () => import('./home/home.module').then(m => m.HomeModule),
      },
      {
        path: 'about',
        loadChildren: () => import('./about/about.module').then(m => m.AboutModule),
      },
      {
        path: '',
        redirectTo: 'home',
        pathMatch: 'full'
      }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

Step 5: Create a Layout Component

Now, let's create a main LayoutComponent to host our navigation and content.

Generate the LayoutComponent:

ng generate component layout

src/app/layout/layout.component.html:

<nav>
  <ul>
    <li><a routerLink="home" routerLinkActive="active">Home</a></li>
    <li><a routerLink="about" routerLinkActive="active">About</a></li>
  </ul>
</nav>
<router-outlet></router-outlet>

Step 6: Update the Main App Component

Update the AppComponent to include the LayoutComponent.

src/app/app.component.html:

<app-layout></app-layout>

Step 7: Add CSS (Optional)

You might want to add some basic styling for the navigation.

src/styles.css:

body {
  font-family: Arial, sans-serif;
}

nav ul {
  list-style-type: none;
  padding: 0;
}

nav ul li {
  display: inline;
  margin-right: 10px;
}

nav ul li a {
  text-decoration: none;
  color: #333;
}

nav ul li a.active {
  font-weight: bold;
  color: #007bff;
}

router-outlet {
  margin-top: 20px;
}

Step 8: Run the Application

Now, you can run your application to see the child routes and lazy loading in action.

ng serve

Navigate to http://localhost:4200 in your browser and you should see the navigation links. Click on "Home" and "About" to see the child routes in action.

Top 10 Interview Questions & Answers on Angular Child Routes and Lazy Loading

Top 10 Questions and Answers on Angular Child Routes and Lazy Loading

2. How do you define child routes in Angular? Child routes are defined within the routes array of a module, nested inside a parent route's configuration. You use the children property to specify the child routes:

const routes: Routes = [
  {
    path: 'blog',
    component: BlogComponent,
    children: [
      {
        path: 'posts',
        component: PostsComponent
      },
      {
        path: 'comments',
        component: CommentsComponent
      }
    ]
  }
];

This setup allows you to navigate to blog/posts and blog/comments, both of which would be displayed within the BlogComponent.

3. What is lazy loading in Angular? Lazy loading in Angular allows you to load feature modules on demand, rather than all at once, which can help reduce the initial load time of your application. It means that the module and its associated routes are loaded only when they are needed. This lazy loading is particularly useful for large applications with distinct sections that can be loaded asynchronously.

4. How do you implement lazy loading for a feature module in Angular? To implement lazy loading for a feature module, you configure the routes in the AppRoutingModule to use the loadChildren property. Here's an example:

const routes: Routes = [
  {
    path: 'blog',
    loadChildren: () => import('./blog/blog.module').then(m => m.BlogModule)
  }
];

In this snippet, the BlogModule will be loaded when the route blog is navigated to.

5. Can you use child routes in combination with lazy loading? Absolutely, you can define both child routes and use lazy loading in your Angular application. Here is how you can do it: In your main AppRoutingModule, set up the lazy loading for the BlogModule:

const routes: Routes = [
  {
    path: 'blog',
    loadChildren: () => import('./blog/blog.module').then(m => m.BlogModule)
  }
];

Then, within the BlogModule, define the child routes:

const routes: Routes = [
  {
    path: '',
    component: BlogComponent,
    children: [
      {
        path: 'posts',
        component: PostsComponent
      },
      {
        path: 'comments',
        component: CommentsComponent
      }
    ]
  }
];

6. What are the benefits of using lazy loading with Angular? Lazy loading in Angular can greatly enhance the performance of your application. By splitting your app into multiple bundles and loading them as needed, you can significantly reduce the initial load time. This is especially beneficial in large-scale applications where users only need to access certain modules under specific circumstances.

7. Are there any disadvantages to using lazy loading in Angular? While lazy loading offers many advantages, it can increase the complexity of your application’s routing configuration. Additionally, not all modules might be as modular, and lazy loading smaller modules might not provide noticeable performance benefits. Furthermore, when using lazy loading, tools like AoT and tree-shaking have to work harder to detect and eliminate unused modules and components.

8. How do you guard lazy-loaded routes in Angular? To guard lazy-loaded routes, you can use route guards. Lazy-loaded routes can be protected just like any other routes. Here’s an example using an AuthGuard:

const routes: Routes = [
  {
    path: 'blog',
    canActivate: [AuthGuard],
    loadChildren: () => import('./blog/blog.module').then(m => m.BlogModule)
  }
];

In this example, the AuthGuard is applied to all routes within the BlogModule.

9. How do you handle preloading in Angular? Preloading in Angular allows you to specify a preloading strategy to load some of your feature modules in the background, after the bootstrapping process. You can use different preloading strategies such as PreloadAllModules to preload all lazy-loaded modules, or a custom strategy:

RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })

Or, if you want to create a custom preloading strategy:

import { Injectable } from '@angular/core';
import { PreloadingStrategy, Route } from '@angular/router';
import { Observable } from 'rxjs';
import { of } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class CustomPreloadingStrategy implements PreloadingStrategy {
  preload(route: Route, load: () => Observable<any>): Observable<any> {
    return route.data && route.data['preload'] ? load() : of(null);
  }
}

And then configure it in your AppRoutingModule:

RouterModule.forRoot(routes, { preloadingStrategy: CustomPreloadingStrategy })

10. What tools or best practices can help you optimize lazy loading in Angular? Optimizing lazy loading involves several strategies:

  • Splitting your code effectively to avoid loading unnecessary modules.
  • HTTP caching to make retrieving lazy-loaded modules faster.
  • Removing unused code via tree shaking to ensure that only necessary parts of your application are loaded.
  • Using tools like Webpack Bundle Analyzer to identify and reduce large module sizes.
  • Lazy loading common modules only when necessary, and using eager loading for critical path modules to ensure a smooth initial load experience.

You May Like This Related .NET Topic

Login to post a comment.