如何将Angular 16的RouterModule.forChild路由代码迁移至Angular 17
Angular 16 路由懒加载代码适配 Angular 17 写法
Angular 17 主推独立组件模式,相比传统 NgModule 更轻量简洁,下面提供两种适配方案:
方案一:改用独立组件(推荐)
1. 将 DashboardComponent 改为独立组件
修改组件代码,添加 standalone: true 标记,并直接导入所需模块:
import { Component } from '@angular/core'; import { CommonModule } from '@angular/common'; @Component({ selector: 'app-dashboard', standalone: true, imports: [CommonModule], templateUrl: './dashboard.component.html', styleUrls: ['./dashboard.component.css'] }) export class DashboardComponent {}
2. 主路由配置中直接懒加载组件
在路由配置文件(如 app.routes.ts)里,用 loadComponent 替代原有的 loadChildren:
import { Routes } from '@angular/router'; export const routes: Routes = [ { path: 'dashboard', // 懒加载独立组件 loadComponent: () => import('./dashboard/dashboard.component').then(m => m.DashboardComponent) } ];
方案二:保留 NgModule 模式(兼容旧代码)
如果想继续使用 NgModule,Angular 17 也支持,可调整路由配置方式:
1. 更新 DashboardModule 代码
可以选择保留原 RouterModule.forChild,或改用新的 provideRouter 方式(推荐后者):
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { DashboardComponent } from './dashboard.component'; import { provideRouter } from '@angular/router'; @NgModule({ declarations: [DashboardComponent], imports: [CommonModule], providers: [ provideRouter([ { path: '', component: DashboardComponent } ]) ] }) export class DashboardModule {}
2. 主路由配置不变
依然使用 loadChildren 懒加载模块:
import { Routes } from '@angular/router'; export const routes: Routes = [ { path: 'dashboard', loadChildren: () => import('./dashboard/dashboard.module').then(m => m.DashboardModule) } ];
内容的提问来源于stack exchange,提问作者shekhar
相关产品推荐
相关产品推荐

