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);
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();
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
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
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
MyWelcomePage
view? I have no idea how to retrieve the view that I want to go to.
Commented
May 12, 2016 at 1:07
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.
There is an Issue with ionic 2 popTo(). The Ionic Team is expected to fix it.
See Links below: https://forum.ionicframework.com/t/viewcontroller-and-popto-ionic-2/53704
It's late but for someone who want it, see https://github.com/ionic-team/ionic/blob/master/src/navigation/nav-controller.ts link.
abstract popTo(page: Page | string | ViewController, opts?: NavOptions, done?: TransitionDoneFn): Promise<any>;
So you can use popTo('pagename' or PageName or index) and with options too.