'Angular - share component among children

// 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.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source