blog, Mobile

Ionic 3 Backup 2 Pages

So in a mobile app I’m developing with Ionic 3 there is a page where there are 4 pages in the navigation stack.  To find this out I ran the following:

console.log(this.navCtrl.getViews());

The output from this was:

(3) [ViewController, ViewController, ViewController]
0: ViewController {component: ƒ, _isHidden: true, _state: 3, willEnter: EventEmitter, didEnter: EventEmitter, …}
1: ViewController {component: ƒ, _isHidden: true, _state: 3, willEnter: EventEmitter, didEnter: EventEmitter, …}
2: ViewController {component: ƒ, _isHidden: true, _state: 3, willEnter: EventEmitter, didEnter: EventEmitter, …}
3: ViewController {component: ƒ, _isHidden: false, _state: 3, willEnter: EventEmitter, didEnter: EventEmitter, …}
length: 4
__proto__: Array(0)

I wanted to “pop” off the top 2 pages (indexes 3,2).

A post on StackOverflow said to simply use the NavController remove function. This function takes the starting index number and then the number or pages to remove. So to test this I created the following function:

goCustomerList() {
  this.navCtrl.remove(3,2);
}

This seemed to make sense that this would start with index 3 (4th item) and remove 2 pages. But when I executed this nothing happened. When I replaced the 2,3 with 3,1 the function did remove the page that I was on. However this is the same functionality as the pop() function.

Then I tried:

goCustomerList() {
  this.navCtrl.remove(2,1);
}

When the stack was logged to the console I noticed that the 3rd page was removed from the nav stack. However, the view never changed.

This was the duh moment when I realized that this makes sense. What if I wanted to stay on the page or push a new page onto the stack but remove previous pages. The remove does not redirect the page, it simply removes pages from the stack.

So the final function that worked was:

goCustomerList() {
  this.navCtrl.remove(2);
  this.navCtrl.pop();
}

I tested this with a page that was 5 pages on the stack and then passing in the startIndex (3) and removeCount (2) and this worked, once the current page is popped off the stack.

Leave a Reply