[Angular2 Router] Lazy Load Angular 2 Modules with the Router
Angular 2 lazy loading is a core feature of Angular 2. Lazy loading allows your application to start up faster because it only needs to use the main App Module when the page initially loads. As you navigate between routes, it will load the additional modules as you define them in your routes. Make sure to properly organize your files into Angular 2’s module pattern so that files that belong to each module don’t get required by other modules.
First we need to arrange the component into different module.
Create Four files
- home.module.ts
- home.routes.ts
- contact.module.ts
- contact.routes.ts
Each modue.ts will the entery file for this module, Angualr2 lazy loads the module in by router.
app.routes.ts:
import {RouterModule} from "@angular/router"; const routes = [ {path: '', loadChildren: 'app/home/home.module'}, {path: 'contact', loadChildren: 'app/contact/contact.module'}, ]; export default RouterModule.forRoot(routes);
Here we use 'loadChildren' instead of 'component'. This helps lazy loading, to deduce the bundle size.
Also we point to the location of the module file for each component.
'forRoot': because app.routes.ts is the main entery point, for each child module, we will use 'forChild'
home.routes.ts:
import {HomeComponent} from "./home.component"; import {RouterModule} from "@angular/router"; const routes = [ {path: '', component: HomeComponent} ]; export default RouterModule.forChild(routes);
home.module.ts:
import {NgModule} from "@angular/core"; import {CommonModule} from "@angular/common"; import {HomeComponent} from "./home.component"; import {SearchBarComponent} from "./search-bar/search-bar.component"; import {ResultListComponent} from "./result-list/result-list.component"; import homeRoutes from './home.routes'; @NgModule({ imports: [ CommonModule, homeRoutes ], declarations: [HomeComponent, SearchBarComponent, ResultListComponent], exports: [HomeComponent, SearchBarComponent, ResultListComponent] }) export default class HomeModule{}
In module file, we import routes.
The same partten for contact component. To prove that, when we click the contact routeLink, we can see from the Devtool Netwrok panel, it load the contact module:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具