Thursday, February 7, 2019

I set up the lazy loading of modules in an Angular 7 application for the first time today and in struggling realized that one has to have a routing module breakout for the lazy loaded module!

I do not remember this from earlier versions of Angular, but here it is. Assuming I have a route like so in my main routing module...

{ path: 'contracts', loadChildren: './modules/contracts.module#ContractsModule' }

 
 

...my ContractsModule could be like so:

import { NgModule } from '@angular/core';
import { ContractsComponent } from '../components/contracts.component';
import { ContractsRoutingModule } from './contracts-routing.module';
@NgModule({
   declarations: [ContractsComponent],
   imports: [ContractsRoutingModule],
   providers: [],
   bootstrap: [ContractsComponent]
})
export class ContractsModule { }

 
 

It needs a supporting ContractsRoutingModule like so:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ContractsComponent } from '../components/contracts.component';
const routes: Routes = [
   { path: '', component: ContractsComponent }
];
@NgModule({
   imports: [RouterModule.forChild(routes)],
   exports: [RouterModule]
})
export class ContractsRoutingModule { }

 
 

Do note the use of .forChild above and not .forRoot as .forRoot is to only appear in the main routing module like so:

imports: [RouterModule.forRoot(routes, { useHash: true })],

No comments:

Post a Comment