Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between getRootNav() and navCtrl() methods

Can you tell me what are the differences of below 2 methods? Which moment should I use it?

book.ts

this.app.getRootNav().push('FromBook', { bookId: this.data.id })

this.navCtrl.push('FromBook', { bookId: this.data.id });

When we use inner components like below sometimes it works.Sometimes it is not.Why this kind of different behavior with above 2 navigation methods?

author-page.html

<div>
        <book *ngFor="let book of authorData?.books" [data]="book"></book>
</div>
like image 788
Sampath Avatar asked Jun 29 '17 10:06

Sampath


1 Answers

Both methods add a new page to the current Nav component, the only difference is to which Nav Controller.

If your app is a Tabs page, with several tabs, each tab has its own Nav component. That's why if you try to push a page from inside of a child tab by doing this.navCtrl.push(ThePage) that new page won't be shown if you switch to another tab, but if you come back to the previous tab, that page will still be visible. That's because the page was pushed to a child Nav component, the Nav component from the single tab.

If you use this.app.getRootNav().push(ThePage), your pushing the new page to the Nav component of the root app, so it doesn't matter if the component where you are doing that has its own Nav component, the Nav from the Root component will be used.

The tab was just an example, the same is valid when you try to push a page from any overlay component (popover, modal, alert, etc)

This is included in the docs:

Navigating from an Overlay Component

What if you wanted to navigate from an overlay component (popover, modal, alert, etc)? In this example, we've displayed a popover in our app. From the popover, we'll get a reference of the root NavController in our app, using the getRootNav() method.

import { Component } from '@angular/core';
import { App, ViewController } from 'ionic-angular';

@Component({
    template: `
    <ion-content>
      <h1>My PopoverPage</h1>
      <button ion-button (click)="pushPage()">Call pushPage</button>
     </ion-content>
    `
  })
  class PopoverPage {
    constructor(
      public viewCtrl: ViewController
      public appCtrl: App
    ) {}

    pushPage() {
      this.viewCtrl.dismiss();
      this.appCtrl.getRootNav().push(SecondPage);
    }
  }
like image 120
sebaferreras Avatar answered Oct 04 '22 22:10

sebaferreras