DEV Community

Tekale Vaishali
Tekale Vaishali

Posted on


Angular9: Lazy loading Components

This article shows you how to lazy load with Angular 9 and provides the code and resources along the way.

1 Create New App

Create a new angular app using Angular CLI command. Below command will create the angular application

 ng new lazy-demo –minimal  –inline-template  –inline-style  –routing=false –style=css

This command will create a new angular app in a folder named lazy-demo

–minimal removes testing frameworks

–inline-template puts all component templates in the .ts file

–inline-styles puts all component styles in the .ts file

–routing=false does not add any routing

–style=css specifies to use CSS

2 Create Components

Create two new components named lazy1 and lazy2

ng generate component Lazy1 –flat –skip-import –skip-selector

ng generate component Lazy2 –flat –skip-import –skip-selector

These commands will create two new components lazy1.component.ts and lazy2.component.ts respectively. We wont want the components to be included in out module file as we want component to lazy loaded. We also don’t need selector as we are not referring them in template directly

3 Lazy Load Component

Add the following code in app.component.ts file. We need to inject ViewContainerRef, ComponentFactoryResolver in our constructor which we are importing from @angular/core

constructor(private viewContainerRef: ViewContainerRef,
private rcf: ComponentFactoryResolver) {
async loadLazy1() {
const { Lazy1Component } = await import(‘./lazy1.component’);
async loadLazy2() {
const { Lazy2Component } = await import(‘./lazy2.component’);

The getLazy1 function clears the container. This is important is we only want to show one of the lazy-loaded components at a time. If we did not clear the container, every time we lazy load components, they would be displayed one after another.

Next, we import the components, lazily, using the await import syntax.

Finally, we create the component in the container.

4. Add Buttons to Lazy Load

Modify template app.component.ts as shown below

<p>Lazy Loading Application</p>
<button (click)=”loadLazy1()”>Load Lazy1</button>
<button (click)=”loadLazy2()”>Load Lazy2</button>

5 Watch Lazy Load

Now run the app with ng serve and browser to http://localhost:4200. After the app loads, open the browser’s developer tools. Then clear the network traffic, so we can see when the components are lazy-loaded.

When you click one of the buttons, notice that the associated component I displayed and the network traffic shows the component is lazy loaded.

Sample code for this tutorial is available on GitHub

Happy Learning!!!!

Top comments (1)

clabnet profile image
Claudio Barca

Why do not use the code block to write the post? Thanks

50 CLI Tools You Can't Live Without

The top 50 must-have CLI tools, including some scripts to help you automate the installation and updating of these tools on various systems/distros.