


Detailed explanation of lazy loading of Angular module instances using routing
This article mainly introduces the detailed explanation of using routing to delay loading Angular modules. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.
Angular is very modular, and a very useful feature of modularity is that modules serve as lazy loading points. Lazy loading means that resources such as a module and all the components it contains can be loaded in the background. This way Angular doesn't need to download all the files from the server on the first screen, and won't download the corresponding module until you request it. This is a huge help in improving performance and reducing the initial download file size above the fold. And it can be set up easily.
A simple example will be used here to demonstrate how this feature works. Split the application into multiple different modules and lazily load them when needed.
Lazy loading routes need to be defined outside the root module, so you need to include the functions that need to be lazy loaded in the function module.
We use Angular CLI to create a demo project: Demo.
ng new demo
Then, enter the demo folder. Install necessary packages.
npm i
After installation, we create a new module shop. In angular CLI, ng is the command prompt instruction, and g stands for generate, which is used to create new items of a certain type.
To create a new module named shop is:
ng g module shop
This will cause a new folder to be created under the src/app file of the Angular project , and add a module definition file named shop.module.ts.
Then, we create components in the default app module and the newly created shop module.
ng g c home/home ng g c shop/cart ng g c shop/checkout ng g c shop/confirm
CLI will allocate home to the app module, and allocate cart, checkout, and confirm to the shop module. For example,
The shop at this time The content of .module.ts is as follows:
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { CheckoutComponent } from './checkout/checkout.component'; import { CartComponent } from './cart/cart.component'; import { ConfirmComponent } from './confirm/confirm.component'; @NgModule({ imports: [ CommonModule ], declarations: [CheckoutComponent, CartComponent, ConfirmComponent] }) export class ShopModule { }
Modify the root component
The app.component.ts component generated by Angular CLI by default is The main page of the application contains some introductory information about Angular. We modify it to what we need. Modify the default generated app.component.html content to the following content.
<!--The content below is only a placeholder and can be replaced.--> <h1>Lazy Load Module</h1> <a [routerLink]="['/shop']" >Shop Cart</a> <router-outlet> </router-outlet>
A placeholder router-outlet is provided here, and each component will be displayed in it.
At the same time, a navigation link is provided that can navigate directly to the /shop/cart component.
Create route
Root route
First create the root route.
We add a routing configuration file named main.routing.ts in the app folder. The content is as follows:
import { Routes } from '@angular/router'; // HomeComponent this components will be eager loaded import { HomeComponent } from './home/home.component'; export const routes: Routes = [ { path: '', component: HomeComponent, pathMatch: 'full' }, { path: 'shop', loadChildren: './shop/shop.module#ShopModule' }, { path: '**', component: HomeComponent } ];
Among them, the home component is loaded in advance normally.
The following points need to be noted:
1. We use loadChildren to delay loading a module. Instead of using components used by early loading.
2. We use a string instead of a symbol to avoid early loading.
3. We not only define the path of the module, but also provide the class name of the module.
Enable root routing in app.module.ts. Mainly you need to use forRoot to enable the root route.
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { HomeComponent } from './home/home.component'; import { routes } from './main.routing'; import { RouterModule } from '@angular/router'; @NgModule({ declarations: [ AppComponent, HomeComponent ], imports: [ BrowserModule, RouterModule.forRoot(routes) ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Module routing
Define module routing
For the shop module, there is nothing to define routing In particular, we can define a route definition file named shop.route.ts here. The content is as follows:
import { Routes } from '@angular/router'; import { CartComponent } from './cart/cart.component'; import { CheckoutComponent } from './checkout/checkout.component'; import { ConfirmComponent } from './confirm/confirm.component'; export const routes: Routes = [ { path: '', component: CartComponent }, { path: 'checkout', component: CheckoutComponent }, { path: 'confirm', component: ConfirmComponent } ];
You also need to modify the module definition file shop. module.ts file to use this route definition. Note that we need to use forChild to enable child routes.
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { CheckoutComponent } from './checkout/checkout.component'; import { CartComponent } from './cart/cart.component'; import { ConfirmComponent } from './confirm/confirm.component'; import { routes } from './shop.routing'; import { RouterModule } from '@angular/router'; @NgModule({ imports: [ CommonModule, RouterModule.forChild(routes) ], declarations: [CheckoutComponent, CartComponent, ConfirmComponent] }) export class ShopModule { }
Everything is ready.
Test lazy loading
Now launch the app.
ng serve
The application will be started on port 4200 by default. Please open the browser and visit: http://localhost:4200/
Network access to visit the homepage As shown below, it does not include the content of functional modules.
We first clear the history of network requests.
Then click the link and when accessing /shop/cart, the network request is as follows. You can see that a new script file is loaded, which contains the delayed loading function module.
Only the function module is loaded.
Related recommendations:
Angular implementation of preloading delay module example sharing
Detailed example of how Angular2 integrates other plug-ins
Advanced Angular Component Pattern Example
The above is the detailed content of Detailed explanation of lazy loading of Angular module instances using routing. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics
![Error loading plugin in Illustrator [Fixed]](https://img.php.cn/upload/article/000/465/014/170831522770626.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
When launching Adobe Illustrator, does a message about an error loading the plug-in pop up? Some Illustrator users have encountered this error when opening the application. The message is followed by a list of problematic plugins. This error message indicates that there is a problem with the installed plug-in, but it may also be caused by other reasons such as a damaged Visual C++ DLL file or a damaged preference file. If you encounter this error, we will guide you in this article to fix the problem, so continue reading below. Error loading plug-in in Illustrator If you receive an "Error loading plug-in" error message when trying to launch Adobe Illustrator, you can use the following: As an administrator

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

Subtitles not working on Stremio on your Windows PC? Some Stremio users reported that subtitles were not displayed in the videos. Many users reported encountering an error message that said "Error loading subtitles." Here is the full error message that appears with this error: An error occurred while loading subtitles Failed to load subtitles: This could be a problem with the plugin you are using or your network. As the error message says, it could be your internet connection that is causing the error. So please check your network connection and make sure your internet is working properly. Apart from this, there could be other reasons behind this error, including conflicting subtitles add-on, unsupported subtitles for specific video content, and outdated Stremio app. like

This article will give you an in-depth understanding of Angular's state manager NgRx and introduce how to use NgRx. I hope it will be helpful to you!

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

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

How to use monaco-editor in angular? The following article records the use of monaco-editor in angular that was used in a recent business. I hope it will be helpful to everyone!

How to turn off the delay in Douyu live broadcast? 1. The user first clicks to enter Douyu Live, as shown in the picture. 2. Then the user clicks "Settings" in the "Douyu Live" window, as shown in the figure. 3. Then in the "Settings" window, click "Advanced", as shown in the figure. 4. Finally, in the "Advanced" window, the user can cancel the delay by turning off "Low latency mode is on by default", as shown in the figure. How to watch replays of Douyu live broadcast? 1. In the first step, we first find the Douyu live broadcast software icon on the computer desktop, then right-click and select the "Open" option. 2. In the second step, after opening the Douyu live broadcast software, we find "Follow" on the left side of the page. option, click to open this option and find a host you like on the right page, click the "Recording" option 3. The third step, proceed
