Search code examples
angularroutesback-buttonionic4

Ionic 4 Angular Back Button to previous page instead of root?


I have a little Ionic 4 App with 2 Tabs and 1 Detail Page. The Problem I'm facing here is that if I go from Tab2 into Detail Page and from there with ion-back-button back it always redirect me to Tab1 instead of Tab2 where I was before.

Here is my example:

Tab2 Html: Here I have a simple ion-item with a click event:

        <ion-item class="chat-item" (click)='openChat()' >

It calls the openChat funtion which works like this:

          openChat() {
            this.router.navigateByUrl('/chatdetail/:uid');
          }

Now it opens my Chatdetail Page in which I have placed a Back Button to navigate back like this:

    <ion-header>
      <ion-toolbar>
          <ion-buttons slot="start">
              <ion-back-button></ion-back-button>
           </ion-buttons>
        <ion-title>chatdetail</ion-title>
      </ion-toolbar>
    </ion-header>

But when I click this Button it doesn't just "pop" the page like it was in Ionic3 instead it directs me to the root page of my App which is Tab1.

Is there any way of overwriting that back event to go to the page I was before?


Solution

  • Update:

    Ionic team has fixed this on Ver: 4.3.0

    Old

    You need to use defaultHref="/Tab2" like so:

      <ion-back-button defaultHref="/Tab2"></ion-back-button>
    

    The url to navigate back to by default when there is no history.

    https://ionicframework.com/docs/api/back-button

    How to go to the previous page?

    import { Location } from "@angular/common";

    constructor(private location: Location) { }

    myBackButton(){
      this.location.back();
    }