4

I have an app of which one can navigate to a page in which there is no way forwards. Think of clicking a program in a TV guide to open a page with that program's details, obviously you will want to go back to the TV guide.

For a button to go backward to the TV guide, I have an <a> tag.

Which would be the most advisable use case for this:

  1. Using href="/guide"

or

  1. Using (click)=goBack() where the function calls location.back()
physicsboy
  • 5,656
  • 17
  • 70
  • 119
  • I would use the "back" method from the location service imported with: import {Location} from '@angular/common'; – Geku Aug 23 '18 at 10:59
  • you can get answer from this link https://stackoverflow.com/questions/35446955/how-to-go-back-last-page/41953992 – mittal bhatt Aug 23 '18 at 11:00
  • 1
    Possible duplicate of [How to go back last page](https://stackoverflow.com/questions/35446955/how-to-go-back-last-page) – NullPointer Aug 23 '18 at 11:03
  • Consider if the user reaches the page by another way. If they click a Google search result that goes directly to the program details page, should the back button take them to the guide page, or back to their Google search results? – Joe Daley Nov 02 '19 at 06:46

2 Answers2

3

You should use built-in Location service of Angular as.

Angular-Location

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


@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.scss']
})

class AppComponent {
    constructor(private location: Location) {
    }
    back() {
        this.location.back();
    }
}
Akj
  • 7,038
  • 3
  • 28
  • 40
2

If you want to navigate in an Angular app, you don't want to use classic href links since they are designed to work for server-rendered apps, but not client-side apps that use the History Javascript API.

Prefer using the RouterLink from Angular.

Between RouterLink and location.back() the choice is yours, it depends whether you want to control the page you want to redirect to, or just want the same behavior as the back button from your browser.

Guerric P
  • 30,447
  • 6
  • 48
  • 86
  • Thanks for the advice. Yeah, `RouterLink` had cropped into my brain, just a case of what somebody had left in the code before I looked at it. I think I may use the `RouterLink` method as `location.back()` didn't appear to be any faster, and it's more legible from the HTML – physicsboy Aug 23 '18 at 12:08