search
HomeWeb Front-endJS TutorialTalk about the use of Angular modules and lazy loading

Talk about the use of Angular modules and lazy loading

Sep 15, 2020 am 10:37 AM
angularLazy loadingmodule

Talk about the use of Angular modules and lazy loading

Related tutorial recommendations: angularjs (Video tutorial)

1. Angular built-in modules

Talk about the use of Angular modules and lazy loading

2. Angular custom module

When our project is relatively small, we don’t need to customize the module. But when our project is very large, it is not particularly appropriate to mount all components into the root module. So at this time we can customize modules to organize our projects. And lazy loading of routes can be achieved through Angular custom modules.

ng g module mymodule

Talk about the use of Angular modules and lazy loading

Create a new user module

ng g module module/user

Create a new root component under the user module

ng g component module/user

Create a new one The address, order, and profile components under the user module

ng g component module/user/components/address
ng g component module/user/components/order
ng g component module/user/components/profile

How to mount the user module in the root module?

Referring to the user component in the template file app.component.html of the app root component will report an error
The following processing is required before it can be accessed

  1. Introduced in app.module.ts Module

Talk about the use of Angular modules and lazy loading

  1. The user module exposes components to be accessed by the outside world
    Talk about the use of Angular modules and lazy loading

  2. Introduce

<app-user></app-user>

in the root template app.component.html. If you need to use the app-address component directly in the root component, you also need to first add it to the user module user.module. ts exposure

/Expose components so that other modules can use exposed components/
exports:[UserComponent,AddressComponent]

How to mount product in the root module What about modules?

Same as above

Create services under user module

  1. Create
    ng g service module/user/services/common

  2. Introducing services in the user module
    user.module.ts

Talk about the use of Angular modules and lazy loading

##Configure routing to implement module lazy loading

Talk about the use of Angular modules and lazy loading

Create a module:


ng g module module/user --routing
ng g module module/article --routing
ng g module module/product --routing

Create a component:


ng g component module/user
ng g component module/user/components/profile
ng g component module/user/components/order
ng g component module/article
ng g component module/article/components/articlelist ng g component module/article/components/info
ng g component module/product
ng g component module/product/components/plist
ng g component module/product/components/pinfo

Let’s take article as an example:

angular configuration lazy loading

Routing in angular can load both components and modules, and what we call lazy loading actually means loading modules. There are no examples of lazy loading of components yet.

To load components, use the component keyword
To load modules, use the loadChildren keyword

1. Create a new app-routing.module.ts

content in the app folder As follows:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
forRoot is used to load routing configuration in the root module,

and forChild is used to load routing configuration in submodules.

Note: You need to import the AppRoutingModule module in the root template app.module.ts

import { AppRoutingModule } from './app-routing.module';
...
imports: [
    AppRoutingModule,
]
2. Configure routing in the submodule

In \module\article\article- Configure routing in routing.module.ts

    import { NgModule } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';

    // import {ArticleComponent} from './article.component';
    const routes: Routes = [
    // {
    //     path:'',
    //     component:ArticleComponent
    // }
    ];

    @NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
    })
    export class ArticleRoutingModule { }
You can also add the routing module when creating a new project, you can omit the above configuration

In article module -routing.module.ts Configure routing

.....

import {ArticleComponent} from './article.component';
const routes: Routes = [
  {
    path:'',
    component:ArticleComponent
  }
];

......
3. Configure routing in the routing module of the app

const routes: Routes = [
  {
    path:'article',
    //写法一:
    loadChildren:'./module/article/article.module#ArticleModule'

    //写法二
    // loadChildren: () => import('./module/user/user.module').then( m => m.UserModule)  
  },
  // {
  //   path:'user',loadChildren:'./module/user/user.module#UserModule'
  // },
  // {
  //   path:'product',loadChildren:'./module/product/product.module#ProductModule'
  // },
  {
    path:'**',redirectTo:'article'
  }
];

If you did not add –routing when creating a new module before , need to configure the routing of the module

product module The routing of product: module\product\product-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import {ProductComponent} from './product.component';
const routes: Routes = [
  {
    path:'',
    component:ProductComponent
  }
];

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

module\product\product.module.ts

import { ProductRoutingModule } from './product-routing.module';

imports: [
    ProductRoutingModule
  ],

user module user’s routing: \module\user\user-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import {UserComponent} from './user.component';
const routes: Routes = [
  {
    path:'',
    component:UserComponent
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class UserRoutingModule { }
user’s module: \module\user\user.module.ts

import {UserRoutingModule} from './user-routing.module';  +

 imports: [
    UserRoutingModule   +
  ],

RouterModule.forRoot() and RouterModule.forChild()

The RouterModule object provides two static methods: forRoot() and forChild() to configure routing information.

The RouterModule.forRoot() method is used to define main routing information in the main module. RouterModule.forChild() is similar to the Router.forRoot() method, but it can only be applied in feature modules.

That is, use forRoot() in the root module and forChild() in the submodule.

Configure sub-routing

    Configure sub-routing in product-routing.module.ts of the product module
  1. import { PlistComponent } from './components/plist/plist.component';
    import { CartComponent } from './components/cart/cart.component';
    import { PinfoComponent } from './components/pinfo/pinfo.component';
    
    const routes: Routes = [
      {
        path:'',
        component:ProductComponent,
        children:[
          {path:'cart',component:CartComponent},
          {path:'pcontent',component:PinfoComponent}
        ]
      },
      {path:'plist',component:PlistComponent}
    ];
    In the product module Template product.component.html Add router-outlet
  1. <router-outlet></router-outlet>
    Add menu to page app.component.html for easy jump
  1. <a>商品模块</a>
    <a>商品列表</a>
More programming related Knowledge, accessible:

programming learning course! !

The above is the detailed content of Talk about the use of Angular modules and lazy loading. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

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 Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),