angular8路由懒加载

angular8路由懒加载

在angular中路由即能加载组件又能加载模块,而我们说的懒加载实际上就是加载模块,目前还没有看到懒加载组件的例子。
加载组件使用的是component关键字
加载模块则是使用loadChildren关键字

例子代码

  1. 父模块路由文件
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { HomeComponent } from './components/home/home.component';

const routes: Routes = [
  {
    path: 'home',
    component: HomeComponent
  },
  //当前版本有两种写法
  { 
    path: 'dynamic',
    loadChildren: './modules/dynamic/dynamic.module#DynamicModule'
    // loadChildren: () => import('./modules/dynamic/dynamic.module').then( m => m.DynamicModule)
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

  1. 子模块Module文件
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { DynamicRoutingModule } from './dynamic-routing.module';
import { DynamicComponent } from './dynamic.component';
import { Tab1Component } from './tab1/tab1.component';
import { Tab2Component } from './tab2/tab2.component';
import { Tab3Component } from './tab3/tab3.component';
import { DynamicDirective } from './dynamic.directive';


@NgModule({
  declarations: [DynamicComponent, Tab1Component, Tab2Component, Tab3Component, DynamicDirective],
  imports: [
    CommonModule,
    DynamicRoutingModule
  ],
  entryComponents: [Tab1Component, Tab2Component, Tab3Component]
})
export class DynamicModule { }

  1. 子模块路由文件
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { DynamicComponent } from './dynamic.component';


const routes: Routes = [
  {
    path: '',
    component: DynamicComponent
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class DynamicRoutingModule { }

注意事项

你可能感兴趣的:(angular)