1
votes

In order to have a clean and DRY ionic project, I just wanted my navbar code to be written in one place, instead of writing the whole HTML in every Ionic page.

For this purpose, I created an Angular component (not an Ionic page) named navbar, and I inject it in my pages. To keep a clean layout with no additional stuff in the DOM, I created a component with the brackets notation, like this:

@Component({
  // brackets let the selector be used as a property instead of a component
  selector: '[navbar]',
  templateUrl: 'navbar.html',
})
export class NavbarComponent {

  @Input() title: string = 'default title';
  constructor() {}

}

Then I try to inject the component in the pages like this:

<ng-container navbar title="My good title"></ng-container>

The purpose is to not create any additional node in the DOM to keep clean layout. But, this DOES NOT WORK, as I get a blank page with no particular error in console.

As a comparison,

<div navbar title="My good title"></div>

works, but my layout is broken (ion content starts from the very top of my page, beeing hidden by navbar)

Any idea? Thanks.

// navbar.html code

<ion-header>
  <ion-navbar>
    <button ion-button menuToggle>
      <ion-icon name="ios-menu"></ion-icon>
    </button>

    <ion-title>{{title}}</ion-title>

    <ion-buttons margin-horizontal end>
      <img class="logo-navbar" src="../../assets/imgs/logo-hudi-noir-noborder.png">
    </ion-buttons>
  </ion-navbar>
</ion-header>

ionic (Ionic CLI) : 4.1.2 Ionic Framework : ionic-angular 3.9.2 @ionic/app-scripts : 3.1.9

1
Are you importing the component module into ionic page module?Aragorn
you need to post the code to your root module. Also, installing the Augury chrome extension will help you debug the issue. I know it has helped me when getting the white screens.Michael Henderson

1 Answers

1
votes

You can apply the navbar attribute to the ion-header element:

<ion-header navbar title="My good title"></ion-header>

and define the NavbarComponent as the content of that element:

<ion-navbar>
  <button ion-button menuToggle>
    <ion-icon name="ios-menu"></ion-icon>
  </button>
  <ion-title>{{title}}</ion-title>
  <ion-buttons margin-horizontal end>
    <img class="logo-navbar" src="../../assets/imgs/logo-hudi-noir-noborder.png">
  </ion-buttons>
</ion-navbar>

See this stackblitz for a demo.