Search code examples
angularangular-routingangular-router

Problem in Nested Routing in Angular Modules


I have a problem in routing with Angular. I wanted to put the login on /login and I did it successfully. My problem is that I wanted to put the Register page on /register

app-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { PrivateLayoutComponent } from './core/layouts/private/private-layout.component';
import { PublicLayoutComponent } from './core/layouts/public/public-layout.component';
import { privateRoutes } from './core/routes/private-layout.routes';
import { publicRoutes } from './core/routes/public-layout.routes';

const routes: Routes = [
  { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
  {
    path: '',
    component: PrivateLayoutComponent,
    children: privateRoutes,
  },
  { path: '', component: PublicLayoutComponent, children: publicRoutes },
];

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

public-layout.routes.ts

import { Routes } from '@angular/router';

// Route for content layout without sidebar, navbar and footer for pages like Login, Registration etc...
export const publicRoutes: Routes = [
  {
    path: 'login',
    loadChildren: () =>
      import('@app/auth/auth.module').then((m) => m.AuthModule),
  },
];

auth-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ForgotPasswordComponent } from './forgot-password/forgot-password.component';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';

const routes: Routes = [
  { path: '', component: LoginComponent },
  { path: 'register', component: RegisterComponent },
  { path: 'forgot-password', component: ForgotPasswordComponent },
];

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

Solution

  • If you want /register to be a route just like /login, you have a few options:

    1. Create another module for the register functionality and lazy load it just like you do with AuthModule.
    2. Stop lazy loading the AuthModule and declare your login and register routes in the AppRoutingModule directly.

    The RegisterComponent can be found on the /login/register path though.