Home Web Front-end JS Tutorial Let's talk about lazily loading modules and dynamically displaying its components in Angular

Let's talk about lazily loading modules and dynamically displaying its components in Angular

Oct 18, 2022 pm 08:46 PM
angular angularjs Lazy loading

How to lazily load a angular module and dynamically create the components declared in it without routing? The following article will introduce the method to you, I hope it will be helpful to you!

Environment: Angular 13.x.x

Angular supports lazy loading of certain page modules through routing. The first reduction has been achieved. The screen size is used to improve the loading speed of the first screen. However, this routing method sometimes cannot meet the needs. [Related tutorial recommendation: "angularjs video tutorial"]

For example, after clicking a button, a row of toolbars will be displayed. I don't want this toolbar component to be packaged into main by default. js, but the component is dynamically loaded and displayed after the user clicks the button.

So why does it need to be loaded dynamically? If the toolbar component is introduced directly into the target page component, then the code in the toolbar component will be packaged into the module where the target page component is located, which will cause the size of the js generated by the module where the target page component is located to become larger; through dynamic lazy loading, the toolbar component can be loaded only after the user clicks the button. In this way, the purpose of reducing the size of the first screen can be achieved.

For demonstration, create a new angular project, and then create a new ToolbarModule. The directory structure of the project is as shown in the figure

In order to achieve the purpose of demonstration, I put a nearly 1m base64 image in the html template of ToolbarModule, and then quoted it directly in AppModuleToolbarModule, and then execute ng build, the execution result is as shown in the figure

##You can see that the packaging size has reached

1.42mb, that is to say, every time the user refreshes this page, regardless of whether the user clicks the display toolbar button, the content related to the toolbar component will be loaded, which causes a waste of resources, so the following will ToolbarModule Remove from the imports declaration of AppModule, and then lazily load the toolbar component when the user clicks the first click to display.

Lazy loading of the toolbar component

First, create a new

ToolbarModule and ToolbarComponent, and declare ToolbarComponent## in

ToolbarModule

#toolbar.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ToolbarComponent } from './toolbar.component';
 
@NgModule({
    declarations: [ToolbarComponent],
    imports: [CommonModule],
    exports: [ToolbarComponent],
})
class ToolbarModule {}
 
export { ToolbarComponent, ToolbarModule };
Copy after login
toolbar.component.ts
import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'toolbar',
    templateUrl: './toolbar.component.html',
    styles: [
        `
    svg {
      width: 64px;
      height: 64px;
    }
    Lets talk about lazily loading modules and dynamically displaying its components in Angular {
      width: 64px;
      height: 64px;
      object-fit: cover;
    }
    `,
    ],
})
export class ToolbarComponent implements OnInit {
    constructor() {}

    ngOnInit(): void {}
}
Copy after login
toolbar.component.html
<p class="flex">
  <svg t="1652618923451" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2104" width="200" height="200"><path d="M412 618m-348 0a348 348 0 1 0 696 0 348 348 0 1 0-696 0Z" fill="#C9F4EB" p-id="2105"></path><path d="M673.19 393h-333a25 25 0 0 1 0-50h333a25 25 0 0 1 0 50zM600.89 235H423.11C367.91 235 323 190.28 323 135.32v-12.5a25 25 0 0 1 50 0v12.5c0 27.39 22.48 49.68 50.11 49.68h177.78c27.63 0 50.11-22.29 50.11-49.68v-16.5a25 25 0 1 1 50 0v16.5c0 54.96-44.91 99.68-100.11 99.68zM673.19 585.5h-333a25 25 0 0 1 0-50h333a25 25 0 0 1 0 50zM467 778H340a25 25 0 0 1 0-50h127a25 25 0 0 1 0 50z" fill="#087E6A" p-id="2106"></path><path d="M739.76 952H273.62a125.14 125.14 0 0 1-125-125V197a125.14 125.14 0 0 1 125-125h466.14a125.14 125.14 0 0 1 125 125v630a125.14 125.14 0 0 1-125 125zM273.62 122a75.08 75.08 0 0 0-75 75v630a75.08 75.08 0 0 0 75 75h466.14a75.08 75.08 0 0 0 75-75V197a75.08 75.08 0 0 0-75-75z" fill="#087E6A" p-id="2107"></path></svg>
  <svg t="1652618941842"
       class="icon"
       viewBox="0 0 1024 1024"
       version="1.1"
       xmlns="http://www.w3.org/2000/svg"
       p-id="2247"
       width="200"
       height="200">
    <path d="M415 624m-348 0a348 348 0 1 0 696 0 348 348 0 1 0-696 0Z"
          fill="#C9F4EB"
          p-id="2248"></path>
    <path d="M695 790H362a25 25 0 0 1 0-50h333a25 25 0 0 1 0 50zM583 649H362a25 25 0 0 1 0-50h221a25 25 0 0 1 0 50zM262 287H129a25 25 0 0 1 0-50h133a25 25 0 0 1 0 50zM262 455.33H129a25 25 0 1 1 0-50h133a25 25 0 0 1 0 50zM262 623.67H129a25 25 0 0 1 0-50h133a25 25 0 0 1 0 50zM262 792H129a25 25 0 0 1 0-50h133a25 25 0 0 1 0 50z"
          fill="#087E6A"
          p-id="2249"></path>
    <path d="M761.76 964H295.62a125.14 125.14 0 0 1-125-125V209a125.14 125.14 0 0 1 125-125h466.14a125.14 125.14 0 0 1 125 125v630a125.14 125.14 0 0 1-125 125zM295.62 134a75.09 75.09 0 0 0-75 75v630a75.08 75.08 0 0 0 75 75h466.14a75.08 75.08 0 0 0 75-75V209a75.09 75.09 0 0 0-75-75z"
          fill="#087E6A"
          p-id="2250"></path>
    <path d="M617 376H443a25 25 0 0 1 0-50h174a25 25 0 0 1 0 50z"
          fill="#087E6A"
          p-id="2251"></path>
    <path d="M530 463a25 25 0 0 1-25-25V264a25 25 0 0 1 50 0v174a25 25 0 0 1-25 25z"
          fill="#087E6A"
          p-id="2252"></path>
  </svg>
  <Lets talk about lazily loading modules and dynamically displaying its components in Angular src="<这里应该是一张大小将近1M的base64图片, 内容较大, 就略去了...>" alt="">
</p>
Copy after login
Then write the code to load the toolbar module in the button click event handler of
AppComponent

:

app.component.ts
import { Component, createNgModuleRef, Injector, ViewChild, ViewContainerRef } from &#39;@angular/core&#39;;

@Component({
    selector: &#39;root&#39;,
    template: `
               <p class="container h-screen flex items-center flex-col w-100 justify-center">
                 <p class="mb-3"
                      [ngClass]="{ hidden: !isToolbarVisible }">
                   <ng-container #toolbar></ng-container>
                 </p>
                 <p>
                   <button (click)="toggleToolbarVisibility()"
                           class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">{{ isToolbarVisible ? &#39;隐藏&#39; : &#39;显示&#39; }}</button>
                   <p class="mt-3">首屏内容</p>
                 </p>
               </p>
             `,
})
export class AppComponent {
    title = &#39;ngx-lazy-load-demo&#39;;
    toolbarLoaded = false;
    isToolbarVisible = false;
    @ViewChild(&#39;toolbar&#39;, { read: ViewContainerRef }) toolbarViewRef!: ViewContainerRef;

    constructor(private _injector: Injector) {}

    toggleToolbarVisibility() {
        this.isToolbarVisible = !this.isToolbarVisible;
        this.loadToolbarModule().then();
    }

    private async loadToolbarModule() {
        if (this.toolbarLoaded) return;
        this.toolbarLoaded = true;
        const { ToolbarModule, ToolbarComponent } = await import(&#39;./toolbar/toolbar.module&#39;);
        const moduleRef = createNgModuleRef(ToolbarModule, this._injector);
        const { injector } = moduleRef;
        const componentRef = this.toolbarViewRef.createComponent(ToolbarComponent, {
            injector,
            ngModuleRef: moduleRef,
        });
    }
}
Copy after login
The key lies in lines 32-42. First, import the module in
toolbar.module.ts

through a dynamic import, and then call createNgModuleRef And pass in the Injector of the current component as the parent Injector of the ToolbarModule, thus instantiating the ToolbarModulegetmoduleRef object, and finally the of the ViewContainerRef object declared in the html template. createComponent method creates ToolbarComponent component<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>private async loadToolbarModule() { if (this.toolbarLoaded) return; this.toolbarLoaded = true; const { ToolbarModule, ToolbarComponent } = await import(&amp;#39;./toolbar/toolbar.module&amp;#39;); const moduleRef = createNgModuleRef(ToolbarModule, this._injector); const { injector } = moduleRef; const componentRef = this.toolbarViewRef.createComponent(ToolbarComponent, { injector, ngModuleRef: moduleRef, }); }</pre><div class="contentsignin">Copy after login</div></div>At this time, let’s take a look at the size of the package after executing <code>ng build

You can see that the first screen size is not as outrageous as it was at the beginning. The reason is that

ToolbarModule and # are not directly imported into

AppModule

and AppComponent ##ToolbarComponent, ToolbarModule are imported into another js file (Lazy Chunk Files). When the Display button is clicked for the first time, this package containing will be loaded. ToolbarModule's js filePay attention to the following gif demonstration. When you click the show button for the first time, there will be an extra pair src_app_toolbar_toolbar_module_ts.js# in the browser network debugging tool. ##File Request

For more programming-related knowledge, please visit: Programming Video

! !

The above is the detailed content of Let's talk about lazily loading modules and dynamically displaying its components in Angular. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

An article exploring server-side rendering (SSR) in Angular An article exploring server-side rendering (SSR) in Angular Dec 27, 2022 pm 07:24 PM

Do you know Angular Universal? It can help the website provide better SEO support!

How to use PHP and Angular for front-end development How to use PHP and Angular for front-end development May 11, 2023 pm 04:04 PM

With the rapid development of the Internet, front-end development technology is also constantly improving and iterating. PHP and Angular are two technologies widely used in front-end development. PHP is a server-side scripting language that can handle tasks such as processing forms, generating dynamic pages, and managing access permissions. Angular is a JavaScript framework that can be used to develop single-page applications and build componentized web applications. This article will introduce how to use PHP and Angular for front-end development, and how to combine them

Detailed explanation of lazy function in Vue3: Lazy loading of components improves application performance Detailed explanation of lazy function in Vue3: Lazy loading of components improves application performance Jun 19, 2023 am 08:39 AM

Vue3 is a popular JavaScript framework that is easy to learn and use, efficient and stable, and is especially good at building single-page applications (SPA). The lazy function in Vue3, as one of the powerful tools for lazy loading of components, can greatly improve the performance of the application. This article will explain in detail the usage and principles of the lazy function in Vue3, as well as its application scenarios and advantages in actual development. What is lazy loading? In traditional front-end and back-end development, front-end developers often need to deal with a large number of

How does Vue implement lazy loading and preloading of components? How does Vue implement lazy loading and preloading of components? Jun 27, 2023 pm 03:24 PM

As web applications become increasingly complex, front-end developers need to better provide functionality and user experience while ensuring page loading speeds. This involves lazy loading and preloading of Vue components, which are important means to optimize the performance of Vue applications. This article will provide an in-depth introduction to the implementation methods of lazy loading and preloading of Vue components. 1. What is lazy loading? Lazy loading means that the code of a component will only be loaded when the user needs to access it, instead of loading the code of all components at the beginning. This can reduce

Token-based authentication with Angular and Node Token-based authentication with Angular and Node Sep 01, 2023 pm 02:01 PM

Authentication is one of the most important parts of any web application. This tutorial discusses token-based authentication systems and how they differ from traditional login systems. By the end of this tutorial, you will see a fully working demo written in Angular and Node.js. Traditional Authentication Systems Before moving on to token-based authentication systems, let’s take a look at traditional authentication systems. The user provides their username and password in the login form and clicks Login. After making the request, authenticate the user on the backend by querying the database. If the request is valid, a session is created using the user information obtained from the database, and the session information is returned in the response header so that the session ID is stored in the browser. Provides access to applications subject to

Angular components and their display properties: understanding non-block default values Angular components and their display properties: understanding non-block default values Mar 15, 2024 pm 04:51 PM

The default display behavior for components in the Angular framework is not for block-level elements. This design choice promotes encapsulation of component styles and encourages developers to consciously define how each component is displayed. By explicitly setting the CSS property display, the display of Angular components can be fully controlled to achieve the desired layout and responsiveness.

Vue lazy loading image failure problem solution Vue lazy loading image failure problem solution Jun 29, 2023 pm 10:42 PM

How to solve the problem of lazy loading failure of images in Vue development Lazy loading (LazyLoad) is one of the optimization technologies commonly used in modern web development. Especially when loading a large number of images and resources, it can effectively reduce the burden on the page and improve the user experience. However, when developing using the Vue framework, sometimes we may encounter the problem of lazy loading of images failing. This article will introduce some common problems and solutions so that developers can better deal with this problem. Image resource path error First, we need to ensure that the image resource

See all articles