Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Check if Location.back has history to go back?

So I have a button that calls, Location.back() i want to show it when it has history available, is it posible to check if location has any history, or can go back?

Or is there a way of accessing the history miself?

Angular Version: 2.2.3

HTML:

<div (click)="historyBack()">
  <i class="fa fa-angle-left"></i>
</div>

component:

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

@Component(...)
export class HomeComponent{
  hasHistory = false;
  constructor(
   private _location: Location
  ){
    this.hasHistory = //Magic code
  }
  historyBack(){
    this._location.back();
  }
}
like image 612
Keff Avatar asked Jan 10 '17 15:01

Keff


2 Answers

In Angular 7 you can use Router.navigated property to check if any navigation event has occurred.

constructor(
  private router: Router,
  private location: Location
) {
  this.hasHistory = this.router.navigated;
}
like image 83
filarrro Avatar answered Oct 14 '22 21:10

filarrro


You can use JavaScript to view the last place the user visited:

document.referrer

doc

So, in your case, you can check if the user can go back, as follows:

historyBack() {
if (document.referrer) {
  this._location.back();
 }
}
like image 41
Baruch Gans Avatar answered Oct 14 '22 22:10

Baruch Gans