Search⌘ K
AI Features

Protecting a Lazy-Loaded Module

Explore how to protect lazy-loaded modules in Angular by using authentication guards that implement the CanLoad interface. Understand how to extend auth guards for lazy-loaded routes and apply lazy loading to standalone components with the Angular router by leveraging the loadComponent property. This lesson helps you control access and optimize loading for Angular applications.

Lazy-loaded modules are standard Angular modules, so we can control their access using guards. We can control unauthorized access to a lazy-loaded module similar to how we can do so in eagerly loaded ones. However, our guards need to implement a different interface for this case, the CanLoad interface.

Using a lazy-loading module in auth guard

We will extend our authentication guard for use with lazy-loaded modules.

  1. Open the auth.guard.ts file and import CanLoadFn from the @angular/router npm package:

import { CanActivateFn, CanLoadFn, Router } from '@angular/router';
Importing CanLoadFn
  1. Add the CanLoadFn ...