Home > OS >  Angular - share component among children
Angular - share component among children

Time:03-09

// APP structure
app (/)
  admin (/admin, this will redirect to /admin/dashboard)
    dashboard (/admin/dashboard)
    users (/admin/users)
// app.component.html

<div>
    <app-logo/>
    <router-outlet></router-outlet>
</div>
// app-routing.module.ts

const routes: Routes = [
    {
        path: "admin",
        loadChildren: () => import("./admin/routing.module").then(m => m.AdminRoutingModule),
    },
];

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

We see that in app.component.html if we add a Logo component it will render in every page. Now I have a route admin with some sub routes:

// admin-routing.module.ts
const routes: Routes = [
    {
        path: "dashboard",
        loadChildren: () => import("./dashboard/dashboard.module").then(m => m.AdminDashboardModule),
    },
    {
        path: "",
        redirectTo: 'dashboard',
        pathMatch: 'full',
    },
    {
        path: "users",
        loadChildren: () => import("./users/users.module").then(m => m.AdminUsersModule),
    },
];

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

In the admin.component.html I add another component Sidebar:

// admin.component.html
<app-sidebar/>
<router-outlet></router-outlet>

I expect to see the sidebar in every page of /admin/dashboard and /admin/users/ but nothing is rendered.

CodePudding user response:

hard to be sure without seeing relevant portion of app routing module, but you probably need something like:

const routes: Routes = [
    {
      path: '',
      component: AdminComponent,
      children: [
        {
          path: "dashboard",
          loadChildren: () => import("./dashboard/dashboard.module").then(m => m.AdminDashboardModule),
        },
        {
          path: "",
          redirectTo: 'dashboard',
          pathMatch: 'full',
        },
        {
          path: "users",
          loadChildren: () => import("./users/users.module").then(m => m.AdminUsersModule),
        },
      ];
   }
]

so that you're actually using the AdminComponent to wrap the admin routes.

  • Related