3

I'm new in Angular 5 and trying to build an app with client side and admin side. So I did some search and made this:

AppRoutingModule

const appRoutes: Routes = [
    {
        path: '',
        loadChildren: 'app/website/public.module#PublicModule'
    },
    {
        path: 'admin',
        loadChildren: 'app/admin/admin.module#AdminModule'
    }
];

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

PublicRoutingModule

const PUBLIC_ROUTES: Routes = [
    {
        path: '',
        component: HomeComponent,
    }
];

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

AdminRoutingModule

const ADMIN_ROUTES: Routes = [
    {
        path: '',
        component: DashboardComponent,
        data: {
            title: 'Dashboard'
        },
        children: [

        ]
    }
];

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

And I have imported AppRoutingModule in AppModule, and also imported PublicRoutingModule in PublicModule, also imported AdminRoutingModule in AdminModule.

When I run the app, there is no errors but the HomeComponent is not been rendered initially. Can anyone tell what's the problem here? Thank you.

2
  • where did you add your router-outlet? can you paste a snippet ? Commented May 2, 2018 at 2:30
  • there are many router outlets: in app.component,html, public.component.html, admin.component.html Commented May 2, 2018 at 16:29

1 Answer 1

2

For lazy load module, I think you should add components' declarations to their own router module.

Example for PublicRoutingModule(same for AdminRoutingModule)

const PUBLIC_ROUTES: Routes = [
  {
    path: '',
    component: HomeComponent,
  }
];

@NgModule({
  declarations: [ HomeComponent ],                       // add declaration
  imports: [RouterModule.forChild(PUBLIC_ROUTES)],
  exports: [RouterModule]
})
export class PublicRoutingModule { }

BTW, while debugging routing problems, you should enable tracing to see what really happened during navigation.

@NgModule({
  imports: [RouterModule.forRoot(appRoutes, { enableTracing: true })],
  exports: [RouterModule]
})
export class AppRoutingModule { }
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you it was helpful. As you suggested but in another way I've added HomeComponent in PublicModule.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.