Angular 'sub' module routing

August 31, 2023 · 3 min readLucian Ciobanu
Tags:AngularTypeScript

I have often come across the need to optimize performance for Angular components or to just better manage components into various modules. The go to solution is creating a new routing module within the 'sub' module and lazy loading it as such:

First, create a new routin.module and reference ' ' path to the component you want shown:

specific-routing.module.ts

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

import { SpecificComponent } from './specific/specific.component';
import { SpecificChildComponent } from './specific-child/specific-child.component';

const routes: Routes = [
  {
    path: '',
    componet: SpecificComponent,
    children: [
      {
        path: 'specific-child',
        component: SpecificChildComponent,
      }
    ]
  }
];

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

The new 'sub' module (specific module) will have a module of it's own which we will use in app.module, as such:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ErrorComponent } from './error-component'; //to create if you needed

const routes: Routes = [
  {
    path: '',
    loadChildren: () => import('/specific/specific.module').then(m => m.SpecificModule),
  },
  {
    path: '**',
    component: ErrorComponent,
  }
];

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

Another good example here is how to use the new 'sub' routing module within the components:

import { ActivatedRoute, Router } from '@angular/router';

//component description

export class Component {
  constructor(private router: Router, private activatedRoute: ActivatedRoute) { }
  
  navigate(): void {
    this.router.navigate(['./specific-child'], { relativeTo: this.activatedRoute})
}

Hope this helped!

Cheers,
Lucian

Picture of author

Web Development & Software Delivery