barteloma
barteloma

Reputation: 6875

How to angular route for sub modules?

I have a dashboard module in my angular application. And my app.module.ts is like following.

@NgModule({
  declarations: [
    AppComponent,
    PageNotFoundComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    DashboardModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

And app-routing.module.ts is

const routes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  { path: '**', component: PageNotFoundComponent }
];

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

And dashboard.route.ts is

const dashboardRoutes: Routes = [
    { path: 'dashboard', component: DashboardComponent }
]

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

But the applciaiton is routing to PageNotFoundComponent always.

Upvotes: 0

Views: 48

Answers (3)

Change order of imports AppRoutingModule and DashboardModule like following.

@NgModule({
  declarations: [
    AppComponent,
    PageNotFoundComponent
  ],
  imports: [
    BrowserModule,
    DashboardModule,
    AppRoutingModule,

  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Upvotes: 0

dexter
dexter

Reputation: 46

Your routing concepts are not correct. Simply put, you have to do:

  • on the app-routing.module.ts:
const routes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  { path: 'dashboard', loadChildren: 'path/to/dashboard.module#DashboardModule' },
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
  • and on the dashboard-route.module.ts:
const routes: Routes = [
    { path: '', component: DashboardComponent }
]

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class DashboardRouteModule {}
  • don't forget you must have a dashboard.module.ts with the class name "DashboardModule" where you import the dashboard-rote.module.ts, in order for this to work.

Upvotes: 1

Ivan
Ivan

Reputation: 32

You need to import the module routing on lazy loading. You can change:

{ path: '', redirectTo: '/dashboard', pathMatch: 'full' }

by

{
    path: '',
    loadChildren:
        '../../dashboard.module#DashboardModule'
}

Docs: Lazy loading

Upvotes: 0

Related Questions