I need an alternative to [navPush]="X" for navigating between views on my app

Hi All,

Hope you are all well :slight_smile: with a great weekend in front of you

Strangely it is only today that I have realised that Ionic actually stores the complete DOM of each page/view that is visited when you use [navPush] in the markup. In hindsight I would have structured my app slightly differently but I am where I am.

What I am concerned with is that if I click between views a lot I end up with a whole lot of stuff like in the attached picture!

This is obviously a stupid waste of resources, and I cannot believe I haven’t spotted this before.

Does anyone know the best practice in this situation? I can see that popping the stack, or doing a setRoot might help, but just wanted to ask first!

Many thanks

Simon

Assuming when you go to page-home you wouldn’t want to navigate backwards from there, I would recommend using setRoot() as you mentioned in your question. This will clear the navigation stack other than the page you specify as the root. Hope this helps!

Hi Chris,

Thanks for that. Yes that’s what I thought whilst I was out running. So I just tested this and in ionViewDidLoad() I tried:

this.navCtrl.setRoot(‘HomePage’);

This had the effect of just repeatedly reloading the homepage, which makes sense. I am guessing that all links to the homepage changed to setRoot instead of navPush… but is there a way to just do it from the homepage?

If you wanted to do it from the homepage rather than refactoring into setRoot, you should be able to use the nav controller’s remove function to clear the stack excluding the most recent page in that lifecycle event. Something like remove(0, navCtrl.length() - 1);. The reference is here https://ionicframework.com/docs/v3/api/navigation/NavController/#remove

Worked a charm, thanks Chris :slight_smile: