Home > Blockchain >  Angular set routing parent and children
Angular set routing parent and children

Time:03-03

I'm very new to Angular and I really need help on routing. This is my folder structure:

enter image description here

There are two different layouts, one is a layout for login page, and one is the main layout like the usual admin page which has sidebar, toolbar, etc.

After login, I expected it to load the dashboard page with main layout, but instead it only show the layout and not the dashboard.

app-routing.module.ts

const accountModule = () => import('./features/account/account.module').then(x => x.AccountModule);
const mainModule = () => import('./features/main/main.module').then(x => x.MainModule);

const routes: Routes = [
  { path: '', loadChildren: mainModule, canActivate: [AuthGuard] },
  { path: 'account', loadChildren: accountModule },

  // otherwise redirect to home
  { path: '**', redirectTo: '' }
];

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

account-routing.module.ts

const routes: Routes = [
  {
    path: '', component: LayoutComponent,
    children: [
        { path: 'login', component: LoginComponent },
    ]
  }
];

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

main-routing.module.ts

const routes: Routes = [
  {
    path: '', component: LayoutComponent,
    children: [
        { path: 'dashboard', component: DashboardComponent },
        { path: 'client', component: ClientComponent },
    ]
  }
];

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

How can I modify the route so that when I access http://localhost:4200 it will show dashboard page with main layout instead of just the layout? Or if it's not possible, redirect it to http://localhost:4200/dashboard? Please help.

CodePudding user response:

In your main-routing.module.ts Use match path full with empty string an redirect you your desired path.

const routes: Routes = [
  {
    path: '', component: LayoutComponent,
    children: [
        { path: 'dashboard', component: DashboardComponent },
        { path: 'client', component: ClientComponent },
    ]
  },
  { path: '', redirectTo: 'dashboard', pathMatch: 'full' },

];

EDIT: Corrected order

const routes: Routes = [
  { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
  {
    path: '', component: LayoutComponent,
    children: [
        { path: 'dashboard', component: DashboardComponent },
        { path: 'client', component: ClientComponent },
    ]
  },
];
  • Related