angular中子路由的配置

2018-12-10  本文已影响0人  nzjcnjzx

新建项目

新建组件

在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 { }

demo地址

上一篇 下一篇

猜你喜欢

热点阅读