Search code examples
angularangular2-routingrouter-outlet

Angular: Adding a side bar to most pages (router) without using root-component?


I know the normal is to have your app-root (root component) have the toolbar, sidebar etc added there and have a <router-outlet> to change the content.

My problem is my root component (app-root) that is injected via the index.html like so

<body>
  <app-root></app-root>
</body>

cannot contain the sidebar, menus etc as I wish to offer a Login Screen (and other screens) that mustn't contain these semi-shared components. So right now my app-root contains a simple <router-outlet> which works great for my login and other pages that must NOT share the shared content i.e. sidebar, menus etc.

I was hoping to use something like auxiliary/child routes but I don't fully understand them. A good scenario would be that the login screen continues to work as is, it gets injected into the router-outlet but all other routes need to inject themselves into the router-outlet as well as some shared content.

<md-sidenav-container class="example-container">
  <md-sidenav #sidenav class="example-sidenav">
    An example of content  in the side bar
  </md-sidenav>

  <div class="example-sidenav-content">

     <!-- All other routes should be injected here -->       

  </div>

</md-sidenav-container>

What should I do here ?

I certainly don't want to place the sidebar, menus in every component by means of copy / paste. It should be shared content.


Solution

  • I would suggest:

    1. Put your shared content in the app-root component and use class hidden or ngif to hide them depends on the activatedRoute.
    2. If you have state like (loggedIn user) that redirect the user from pages that do not contain the shared content to pages that contain the shared content, you can divide your application to two modules, set all pages with shared content on module and create mini-app-root component on that module with all shared content and router-outlet.
    3. Create component that contains all shared stuff and router-outlet and in the route.module use load children to navigate to any component.