Home > Back-end >  How to configure Angular module for multiple Child components
How to configure Angular module for multiple Child components

Time:11-17

In my Angular project I have a requirement to create a separate section for Admin and keep all the components there... Now I created a separate module for this but not able to render components based on the routing...

My Code: components

  1. Admin profile component
  2. Admin subscription component

now on the module ... Create admin module and routing.module.ts.

 const routes: Routes = [
  { path: '/profile', component: ProfileComponent },
  { path: '/subscription', component: SubscriptionComponent },
];

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

Now on the app.module.ts I config the routing as:

path: 'admin',
    loadChildren: () =>
      import('./modules/admin/admin.module').then(
        (m) => m.adminModule
      ),
    canActivate: [AuthGuard],

Result I want:

url: admin/profile => load profile component
url: admin/subscription => load subscription component.

Please guide.

CodePudding user response:

You can add admin route in your app-routing main file and add module their, like this:

app-routing.module.ts

...
{
    path: 'admin',
    loadChildren: 'app/modules/admin/admin.module#AdminModule',
    canActivate: [AuthGuard],
    canActivateChild: [AuthGuard], // Add this if you have authguard for child routes as well.
}
...

admin.routing.module.ts

...
{
    path: '',
    component: LayoutComponent,
    children: [
        { path: '', redirectTo: 'profile', pathMatch: 'full' },
        { path: 'profile', component: ProfileComponent },
        { path: 'subscription', component: SubscriptionComponent },
        { path: '**', redirectTo: '' }
    ]
}
...

LayoutComponent.html

<main>
<router-outlet></router-outlet>
</main>

I hope you get the point, if not then comment your question down; will happily help out.

  • Related