Ionic Components are not destroyed after navigation to another page

If you use Ionic routing (<ion-router-outlet> and { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }), as mentioned in the other answer, Pages are cached and navigating to other page, ngOnDestroy is not being called.

If you dont want that, use navigateRoot() from NavContrller:

this.navController.navigateRoot(['some-route']);

And users will not be able to swipe back to the previous page.


Ionic cache pages on navigation and destroy and init hooks doesn't work.

If you need to do some actions on navigation you need to use ionic-router-outlet hooks.

  • ionViewWillEnter - Fired when the component being routed to is about to animate in.
  • ionViewDidEnter - Fired when the component being routed to has animated in.
  • ionViewWillLeave - Fired when the component being routed from is about to animate.
  • ionViewDidLeave - Fired when the component being routed from has animated.

You doesn't need to use any interfaces like OnInit or OnDestroy. Just use a hook.

Example:

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent {
  ionViewDidLeave() {
    // Do actions here
  }
}

I finally figured out why.

  • I completely removed ionic from the application and use only Angular router for navigation.

Now ngOnDestroy is being called every time i navigate to another page and the page itself is removed from the DOM.


I am using ionic 4 and angular. What worked for me is adding { replaceUrl: true } to navigation

this.router.navigate([page.url], { replaceUrl: true });

or on template

<a [routerLink]="page.url" replaceUrl="true">...