Angular - Module for Routes

03/10/2021, Wed
Categories: #typescript
Tags: #Angular

Organize Routes into Modules

In Angular, to make routing cleaner, routes may be defined inside modules to localize the path definition to where a specific component is associated.

Here, we have the "/useful/" route and nested child route of "/useful/stuff" defined for our "useful component".

//useful.module.ts

import { UsefulComponent } from "./useful.component";
import { NgModule } from "@angular/core";

import { RouterModule } from "@angular/router";
const routes = [
  {
    path: "",
    component: UsefulComponent,
    children: [{ path: "stuff", component: UsefulComponent }],
  },
];

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

By convention, there is a dedicated "app-routing.module" defined for aggregating all the routes for the application. The "useful" path is defined in this module and is lazily loaded with the "loadChildren" key definition.

//app-routing.module.ts

import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";

import { HomeComponent } from "./home/home.component";

const routes: Routes = [
  { path: "", component: HomeComponent },
  {
    path: "useful",
    loadChildren: () =>
      import("./useful/useful.module").then((m) => {
        return m.UsefulModule;
      }),
  },
];

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

The "app-routing.module" is loaded into the main "imports" key of the "app.module" file.

//app.module.ts

@NgModule({
  declarations: [AppComponent, HomeComponent],
  imports: [BrowserModule, HttpClientModule, AppRoutingModule],
  bootstrap: [AppComponent],
})
export class AppModule {}

Although, lazily loaded modules require more effort to set up as to plain defining the module directly into the "imports" key of the "app.module", there is the added benefit of excluding data loading for other paths since you only need the data for the current path that you are on. It becomes more useful when your application grows over time.