Destroy ionic page on navigation change

How to destroy the previous page content when navigation change from one page to another page.
I am unable to destroy the previous page when routing to another page like this._router.navigate([’/setting’]) from home page.

When the page is navigated back from setting page to home page content remains the same but I want to clear them.

destroy ? you mean resetting the values or refreshing with new values? @shilpakaramar

I mean initialize new view every time so that ngoninit is called

whatever the code you have used inside the ngonInit can you move into ionViewWillEnter() method and check?

It wil not destroy the dom. Ionic add the page in stack memory and it loads from there. What i need is to completely load new page instead from stack memory

You should check out these navigation options

https://angular.io/api/router/NavigationExtras

Not that anybody need care about my opinion, but FWIW I consider this squarely within the realm of “framework stuff that app developers should not rely on behaving any particular way”. If the framework (or the underlying OS) decides “it would improve UX to cache pages”, so be it. Conversely, if it is decided “hey, we need some resources and are going to nuke some hidden elements out of the DOM at random points”, OK.

Every time I personally have encountered a situation where I would want to do something like OP is requesting, it boiled down to stale data being held in page controllers. Along the lines of:

class Page {
  thingy: Thingy = {};

  ngOnInit(): void {
    thingy = this.service.getThingy();
  }
}

…now we go to some other page, which somehow modifies thingy, but when we come back to this page, it’s still displaying the old thingy. An idiomatic way around this is to refactor the service to return Observable<Thingy>:

class Page {
  thingy$: Observable<Thingy>;

  constructor(thingies: ThingyService) {
    this.thingy$ = thingies.watchThingy();
  }
}

Now any changes are going to be reflected automatically in this page, regardless of when it is cached or evicted from cache. We are no longer at the mercy of any framework lifecycle event timing.

1 Like