6

I want to add a back button in Ionic4(Angular 7). But I can't find the proper method in Angular Router.

import {Router} from '@angular/router';

How do we go back when clicking a button, in the component handler? I'd like to implement it using '@angular/router' not '@angular/common' => Location

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
Valeri
  • 1,072
  • 5
  • 14
  • 31
  • https://stackoverflow.com/questions/35446955/how-to-go-back-last-page – nircraft Apr 10 '19 at 14:46
  • Possible duplicate of [Angular 5 - Which should I use to navigate backward - href or location.back()?](https://stackoverflow.com/questions/51984177/angular-5-which-should-i-use-to-navigate-backward-href-or-location-back) – nircraft Apr 10 '19 at 14:46
  • I want to go back without using Location, just with @angular/router. – Valeri Apr 10 '19 at 14:48

3 Answers3

7

Since you are using ionic 4 then to go backward, you can do the following:

constructor(private navCtrl: NavController) {}

btnClick(){
this.navCtrl.navigateBack('/home'); 
} 
Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
  • 2
    Wouldn't it be more appropriate to use `location.back()` from `@angular/common` when OP is using angular routing? (see https://angular.io/api/common/Location) – Fabian N. Apr 20 '19 at 23:35
  • 1
    It is being called when u use`navigateBack()`, ionic uses it in there code – Peter Haddad Apr 21 '19 at 04:43
  • 2
    I just realized that when you use `location.back()` directly you don't get a proper back animation. – Fabian N. May 17 '19 at 14:10
5

With Angular routing you could use the Location API:

constructor(private location: Location){}

and then when you need to navigate back call:

this.location.back();

Keep in mind that for Angular 7 you have to import Location from @angular/common

Andrew Pomorski
  • 121
  • 2
  • 10
1

Just do the following if you wanna go back to your previous route.

constructor(private navCtrl: NavController) {}

goBack(){
 this.navCtrl.pop(); 
} 

This'll pop the current page from the navigation stack and return you to the previous page and the part of the page from where you had navigated forward.