Skip to content Skip to sidebar Skip to footer

How To Use Nav.popto() (ionic 2)?

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; th

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:

letindex: number;
letviews: any[] = this._navCtrl.getViews()
letfound: 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

Solution 4:

nav.popTo() is for stepping back several levels in your page hierarchy.

For example, if your page hierarchy is login -> welcome -> article1 -> detail1 you might use something like:

constructor(nav: NavController) {
this.nav = nav;

this.nav.popTo(MyWelcomePage);

To go back to your welcome page. See docs for further nav methods and details: http://ionicframework.com/docs/v2/api/components/nav/NavController/#popTo

Solution 5:

Why not just use Ionic's nav.setRoot(@component)?

Taking the above example, you could easily do

nav.push(welcome) -> nav.push(article1) -> nav.push(detail1)

and to go back to the welcome page, just simply nav.setRoot(welcomePage)

Edit: I think this resets the stack.

Post a Comment for "How To Use Nav.popto() (ionic 2)?"