在Angular中,懒加载模块会在加载时编译。当使用懒加载模块时,只有在路由导航到该模块时,才会加载和编译该模块的组件。
下面是一个包含代码示例的解决方法:
LazyModule
的懒加载模块。// lazy.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { LazyComponent } from './lazy.component';
@NgModule({
declarations: [LazyComponent],
imports: [
CommonModule,
RouterModule.forChild([
{ path: '', component: LazyComponent }
])
]
})
export class LazyModule { }
LazyComponent
的懒加载组件。// lazy.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-lazy',
template: 'Lazy Component
',
})
export class LazyComponent { }
AppModule
。// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: 'lazy', loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule) }
];
@NgModule({
imports: [BrowserModule, RouterModule.forRoot(routes)],
declarations: [],
bootstrap: []
})
export class AppModule { }
Lazy Component
这样,当用户点击“Lazy Component”链接时,懒加载模块将被加载和编译,并在
中显示LazyComponent
。
上一篇:Angular的快速路由