How to have a sidebar that can take any component inside?

Viewed 1202

I'm new to angular and I'm trying to create a website.

I have my nav bar and side bar that is a single component, but I would like to have inside my navbar/sidebar component the components that represent a page.

so everytime I navigate to a page I load that page component, and that page component has the "always the same nav bar/side bar" and inside the navbar we have the specific component.

does this makes sense? is it possible?

the dumb solution is to copy the navigation code to each component which represents the page, in order i can have the nav bar in all "pages". but if you need to change something you need to change everywhere.

1 Answers

I think you are looking for this https://angular.io/guide/router-tutorial

You can use the components as routes using RouterModule, you just need to pay attention to point out the correct component.

Example:

Your src/app/app.module.ts will look something like this:

Note: Don't forget to import { RouterModule } from '@angular/router'; and also your components:

import { ComponentOne } from 'app/components/ComponentOne.component';
import { ComponentTwo } from 'app/components/ComponentTwo.component';

    imports: [
      BrowserModule,
      RouterModule.forRoot([
        {path: 'route-one', component: componentOne},
        {path: 'route-two', component: componentTwo},
      ]),
    ],

When you do this, you will now be able to use router-outlet directive in your src/app/app.component.html. router-outlet is where all your components (declared in RouterModule) will be rendered.

This is an example of how your src/app/app.component.html might look (with the Navbar and Sidebar "shared" between the pages):

<div class="wrapper">
    <div class="shared-component">
        <navbar-cmp></navbar-cmp>
    </div>
    <div class="main-panel"> 
        <router-outlet></router-outlet> // Here's your Page.
    </div>
</div>

Another Note: I highly recommend that you create one component for your Navbar and another one for your Sidebar; it will help you to create a better structure and ensure better maintainability.

Related