Ionic 2 - global NavBar for the app

Viewed 15260

In Ionic 1, we have the ability to define an <ion-nav-bar> above an <ion-nav-view>, which serves as a generic nav bar for the entire app and we could turn it off on a per-view basis (using ionNavView's hideNavBar=true|false.

It appears in Ionic 2 we have to insert an <ion-nav-bar> per page - and cannot have a global nav bar for the entire app. Is that correct, or am I missing a trick?

If so - it seems like a lot of duplicated code?

Also, it appears you do not have the ability for the NavBar to build its own back button, and you have to write the own mark-up for the back button yourself (per page) which, again, seems like a lot of code duplicate.

4 Answers

I had a similar issue creating an Ionic 4+ app (@ionic/angular 4.6.2), I wanted to add a login button and some other global stuffs in the header.

You can achieve that in a quite simple way.

Just add a ion-header containing a ion-toolbar in your app.component.html as a global header, like this:

<ion-header class="page-header">
   <ion-toolbar id="main-toolbar">
      <ion-title>
        <ion-label>{{ pageTitle }}</ion-label>
      </ion-title>
      <!-- add here all the things you need in your header --> 
   </ion-toolbar>
</ion-header>
<ion-router-outlet id="content" main></ion-router-outlet>

The problem here is that the "global header" will overlay the content of any page if you do only that. So has a workaround just add an empty ion-header containing an empty ion-toolbar on top of all your pages before the content tag, as follow:

<ion-header>
  <ion-toolbar></ion-toolbar>
</ion-header>
<ion-content>
  <!-- your content here -->
</ion-content>

Doing that the "global header" will overlay the page header and the content will begin just after it.

Then you can manage all the code for your global header controls in your app.component.ts file.

I guess there could be some strange behaviour if the main header has a height greater than the "standard" toolbar height but with some nice CSS you should be able to fix it.

Furthermore, this workaround works fine with a side menu.

Hope it helps!

Related