Angular学习:模块和组件的动态加载

可以利用路由的loadChildren来动态加载angular模块和组件。


1. 建立一个要动态加载的模块(包含相应的组件)

dyn-plugin.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { DynPluginRoutingModule } from './pfc-plugin-routing.module';
import { DynPluginComponent } from './pfc-plugin.component';

@NgModule({
  imports: [
    CommonModule,
    DynPluginRoutingModule
  ],
  declarations: [DynPluginComponent],
  exports: [DynPluginComponent]
})
export default class DynPluginModule { }

注意:要有default 。

组件的代码就省略了。


2. 通过路由的loadChildren来动态加载模块。

guimain-routing.module.ts

let baseRoute: Route = {
        path: '',
        component: GuimainComponent,
        children: [
            {
                path: '',
                redirectTo: 'dashboard',
                pathMatch: 'full'

            },
            {
                path: 'config',
                component: MainconfigComponent
            },
            {
                path: 'dashboard',
                component: DashboardComponent
            }
        ]
    }

 let appendRoute: Route = {
         path: '',
         component: GuimainComponent,
         children: [
             {
                path: 'plugin',
                loadChildren: 'app/plugin/dyn-plugin/dyn-plugin.module'
             }
         ]
}

let rtnRoutes: Routes = [baseRoute, appendRoute];


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


你可能感兴趣的:(Angular学习:模块和组件的动态加载)