How to use nav.popTo() (ionic 2)?

19,779

Solution 1

Here is the code to go up two levels, that is to the parent page of the previous page.

this.navCtrl.popTo(this.navCtrl.getByIndex(this.navCtrl.length()-3));

Pop to the root page.

this.navCtrl.popToRoot();

Solution 2

you mast get index this.navCtrl.getByIndex(int i) and set it inside the popTo(), see the code bellow:

this.navCtrl.popTo( this.navCtrl.getByIndex(1));

with this example, you can pop two pages

Solution 3

If you're lazy loading you'll need something like this:

let targetView = this._navCtrl.getViews().filter(view=> view.id == 'MyAwesomePage')
targetView.length ? this._navCtrl.popTo(targetView[0]) : this._navCtrl.pop()

Note that you may handle the off case with something other than just a pop()

If you want more control on which instance of the view you want to go to, you can try something like this:

let index: number;
let views: any[] = this._navCtrl.getViews()
let found: boolean = views.some((view, i) =>{
  index = i
  return (view.id == 'MyAwesomePage')
})
found ? this.navCtrl.popTo(views[index]) : this._navCtrl.pop()

You may getViews().reverse().filter() or views.reverse().some() to get last occurrences.

This is using Ionic 3 and Array.some() from ES5

Share:
19,779

Related videos on Youtube

Ignat
Author by

Ignat

Updated on June 26, 2022

Comments

  • Ignat
    Ignat almost 2 years

    I'm using NavController. To go back I can use nav.pop(), but how to use nav.popTo() if I need go to the other page (not last)?

    constructor(nav: NavController) {
    this.nav = nav;
    
    this.nav.push(MyNextPage);
    
  • Rosdi Kasim
    Rosdi Kasim almost 8 years
    Hi can you show how to retrive that MyWelcomePage view? I have no idea how to retrieve the view that I want to go to.
  • macio.Jun
    macio.Jun over 7 years
    Your MyWelcomePage needs to be ViewController type which was passed into your detail1-page via NavParams all the way from the welcome-page
  • Sandeep Sharma
    Sandeep Sharma about 7 years
    Thankyou.. this.navCtrl.getByIndex(int i) is working in Ionic 3. Previously in Ionic 2 I was using this.navCtrl.popTo(0) and it stopped working when I upgraded to Ionic 3.
  • Luckylooke
    Luckylooke over 6 years
  • Jeff Fischer
    Jeff Fischer over 6 years
    It's gone dark on their documentation. lmao! :(