Best way to include navbar in Angular?

Viewed 2375

Which is the best approach to show a navbar in my Angular App?

For now i've added my nav-bar component at top of app.component.html and by subscribing to a service i'm setting if some items in navbar should or shouldn't be visible..

My app.component.html looks like this:

<app-top-bar></app-top-bar> // navbar
<div class="container px-0 px-sm-3">
  <router-outlet></router-outlet>
</div>

But at this point i had a doubt if it was better to include app-top-bar in each component and just pass to it as input if the items should or shouldn't be visible in it..

2 Answers

My standard way to do this is in the routing configuration.

You can set your layout component as the parent of pages components.

A simple layout component template could look like this:

<header>
  The header
</header>

<main>
  <!-- Your pages are rendered here -->
  <router-outlet></router-outlet>
</main>

<footer>
  The footer
</footer>

And the routes declaration cool look like this:

const routes = [
  {
    component: LayoutComponent,
    path: '',
    children: [
      { component: PageComponent, path: 'page' }
    ]
  },
  { component: OtherPageComponent, path: 'otherpage' }
];

In the above example PageComponent will be displayed using the LayoutComponent while OtherPageComponent will be rendered without it. That way you can choose when to display the layout based on the current route.

If for a same route the topbar can be shown or hidden, to me this is a state thing so storing that in a Subject in a service makes sense.

I think you are on the correct way. You can define your boolean field to show or hide the app bar as below userIsLogged.

<app-top-bar *ngIf="userIsLogged == true"></app-top-bar> 
<div class="container px-0 px-sm-3">
  <router-outlet></router-outlet>
</div>
Related