新建项目
- ng new project
新建组件
- ng g c home
- ng g c some
- ng g c some/child1
- ng g c some/child2
-
在some中新建模块文件和路由文件结构如下:
image.png
在some.module.ts文件中
- 引入子组件注入路由模块
import { SomeComponent } from './some.component';
import { Child2Component } from './child2/child2.component';
import { Child1Component } from './child1/child1.component';
import { NgModule } from '@angular/core';
import { SomeRoutingModule } from './some.routing';
@NgModule({
declarations: [
Child1Component,
Child2Component ,
SomeComponent
],
imports: [
SomeRoutingModule
]
})
export class SomeModule {}
在some.routing.ts模块中
- 引入路由模块和子组件配置子路由导出
import { Child2Component } from './child2/child2.component';
import { Child1Component } from './child1/child1.component';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { SomeComponent } from './some.component';
const route: Routes = [
{
path: '',
component: SomeComponent,
children: [
{path: 'child1', component: Child1Component},
{path: 'child2', component: Child2Component}
]
}
]
@NgModule({
imports: [
RouterModule.forChild(
route
)
],
exports: [
RouterModule
]
})
export class SomeRoutingModule {}
在app-routig.module.ts中通过loadChildren导入进来,这里可以是从app开始的路径也可以是相对路径
import { HomeComponent } from './home/home.component';
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [
{path: '', component: HomeComponent},
{path: 'some', loadChildren: './some/some.module#SomeModule'}
// 'app/some/some.module#SomeModule' 这样也可以
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
在app.module.ts文件中不需要引入关于子组件相关的组件和模块
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
- 在主路由使用RouterModule.forRoot,在子路由使用RouterModule.forChild
网友评论