Is there a way to determine if there is history in Location.back in Angular 2 in order

I have a button that triggers Location.back(). I only want to show this button when there is history available. Is there a way to check if the location has any history, or if it can go back?

Alternatively, is there a method for me to access the history myself?

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();
  }
}

Answer №1

If you are working with Angular 7, the Router.navigated property is a handy way to determine if any navigation events have taken place.

constructor(
  private router: Router,
  private location: Location
) {
  this.hasNavigated = this.router.navigated;
}

Answer №2

After experimenting with various solutions that were available-

  1. this.router.navigated consistently returned true unexpectedly (possibly due to navigating to another page using redirectTo in routing).
  2. I attempted to use history.length, but it always yielded a value of 2.
  3. Next, I explored the option of utilizing history.state to determine if any arbitrary data was present, indicating a fresh tab without history. However, this only set {navigationId: 1} (by Angular), making it ineffective for refreshing an existing tab with previous history.

Ultimately, I devised a solution using sessionStorage that proved to be effective for my scenario.

In a global context (specifically in app.component.ts), I implemented the following-

ngOnInit(): void {
    this.router.events.pipe(
        filter(event => event instanceof NavigationEnd),
    ).subscribe(() => {
        let navigations = parseInt(sessionStorage.getItem('totalNavigations'), 10) || 0;
        navigations++;
        sessionStorage.setItem('totalNavigations', navigations.toString());
    });
}

When checking for history before navigating back, I utilize this approach-

goBack(): void {
    const totalNavigations = parseInt(sessionStorage.getItem('totalNavigations'), 10);
    if (totalNavigations > 1) {
        this.location.back();    // Or history.back()
    } else {
        this.router.navigateByUrl('/my-default-path')
    }
}

Answer №3

If you're looking to track the user's previous page using JavaScript, you can do so easily:

document.referrer

Here

To enable users to navigate back, you can implement a function like this:

historyBack() {
if (document.referrer) {
  this._location.back();
 }
}

Answer №4

Dealing with a situation where I have a component containing a "go back" button that I don't want to display if the history is empty or if the app is initially started from this specific view.

We experimented with different approaches such as using rxjs to listen for route changes, utilizing Router.navigated, and other methods. However, the most reliable solution we found in various scenarios was using getState() from the Location service.

this.location.getState() retrieves {navigationId: 1}, which remains consistent even when opening a new tab and navigating to the view.

Interestingly, it works perfectly when duplicating the tab as the very first view.


If you prefer not to use Angular's Location class, you can access the same object through window.history

Answer №5

When using Google Chrome, executing this.location.back() on a new tab redirects to a search engine.

In contrast, Firefox takes me to a blank tab in the same scenario.

Both outcomes are acceptable, so I believe there's no need for verification. It should be safe to always utilize this.location.back().

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is jest the ideal tool for testing an Angular Library?

I am currently testing an Angular 9 library using Jest. I have added the necessary dependencies for Jest and Typescript in my local library's package.json as shown below: "devDependencies": { "@types/jest": "^25.1.3", "jest": "^25.1.0", ...

What advantages could learning ReactJS first give me before diving into NextJS?

Just mastered TS and now faced with the decision of choosing a framework. I'm curious why it's recommended to learn ReactJS before NextJS. I've read countless articles advising this, but no one seems to delve into the reasons behind it. Ca ...

Discriminator-based deserializer with strong typing

Seeking advice on how to effectively utilize TypeScript for strongly typing a function that operates similarly to the following example: function createDeserializer(typeDeserializers) { return (data) => { const deserializer = typeDeserializ ...

What are some ways to conceal methods within a class so that they are not accessible outside of the constructor

I am a newcomer to classes and I have written the following code: class BoardTypeResponse { created_on: string; name: string; threads: string[]; updated_on: string; _id: string; delete_password: string; loading: BoardLoadingType; error: Bo ...

Angular 2 encountered a fatal error: Issues with parsing the template:

Here is the code snippet I am currently working with: <div class="container"> <div [hidden]="loggedIn"> <md-grid-list cols="6" [style.margin-top]="'20px'"> <md-grid-tile [colspan]="1"></md-grid-tile> I have already ...

Tips for defining a function across a Angular project

I have the following configuration set up in an Angular5 project using Angular-cli 1.5 within typings.d.ts declare interface String { toSentenceCase(): string; } declare function _debug(o, message?, type?): void; inside app/core/common.ts String.pro ...

Is there a way to include the present date and time within a mat-form-field component in Angular?

I'm working on a mat-form-field to display the current time inside an input field. I've managed to insert it, but I'm struggling with the styling. Here's the snippet of code I'm using: <mat-label>Filing Time:</mat-label> ...

The function is receiving an empty array of objects

This code is for an Ionic app written in typescript: let fileNames: any[] = []; fileNames = this.getFileNames("wildlife"); console.log("file names:", fileNames); this.displayFiles(fileNames); The output shows a strange result, as even though there ar ...

VSCode does not show errors in TSX files by default

As I develop my Next.js app with TypeScript, one major issue I encounter is the lack of immediate feedback on syntax errors in .tsx files. It's frustrating to only discover errors after opening each file or waiting for the project to break down. In a ...

Strategies for Handling Errors within Observable Subscriptions in Angular

While working with code from themes written in the latest Angular versions and doing research online, I've noticed that many developers neglect error handling when it comes to subscription. My question is: When is it necessary to handle errors in an ...

Typescript iterative declaration merging

My current project involves creating a redux-like library using TypeScript. Here is an example of the basic action structure: interface ActionBase { type: string; payload: any; } To customize actions for different types, I extend the base interface. ...

The dependency that was installed in the node_modules directory is now showing as missing the

I have encountered an issue with 2 TS packages. The first package, project-1, is installed as a dependency in the second package, project-2. While I am able to import and access all type definitions of project-1 in project-2, the dependencies (node_modules ...

Incorporating HttpClient in the ngOnInit method of Angular allows for the seamless retrieval of JSON data and its conversion into

Whenever I initialize the HttpClient(this.http) to retrieve data in the ngOnInit() method: ngOnInit(): void { this.http.get('http://127.0.0.1:3000/getData').subscribe((data) => { const type = this.route.snapshot.paramMap.get(' ...

Issue: The element '[object Object]' is of type 'object', which is not supported by NgFor. NgFor only works with Iterables like Arrays. - Problem encountered in an Ionic Project

I'm currently working on retrieving my user's username from Firebase Firestore Database using Ionic and AngularFire. I have implemented the valueChanges() method to obtain the observable and am trying to process it using an async pipe. However, u ...

After executing "npm run dev" in Svelte and Vite, a common error message of "HTMLElement is not defined" might appear

Incorporating several web components into my Svelte project led to the appearance of an error message stating HTMLElement is not defined after running npm run dev (which actually translates to vite dev). The complete error message reads as follows: HTMLEl ...

In Angular, how do outputs impact parents when data consistently travels down from the root?

I have a question that may seem simple, but I am really trying to understand unidirectional data flow in Angular thoroughly. If change detection always happens from top to bottom, how does @Output impact a parent component? Could I be mistaken in my assu ...

TestingCompilerFactory is not available as a provider

Currently troubleshooting my test file to identify the issue that is hindering a successful test run: import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { Component, Directive, Input, OnInit } from '@angula ...

Issue with default behavior of infinite scroll in Angular 4

I'm currently working on incorporating infinite scroll into my Angular 4 application. I've carefully followed all the guidelines provided on https://www.npmjs.com/package/ngx-infinite-scroll According to the documentation: By default, the dir ...

"Privileged" and "shared" within an Angular module

Without adding private before foo, loadBar, andtext, they are considered to be public by default in the component. export class RandomComponent { @Input() foo: string; @Output() loadBar = new EventEmitter(); text: string; } Is there any scenario whe ...

What is the best approach for submitting a form with data through a POST request in an Ionic application?

I am facing an issue while trying to make a POST request in Ionic for submitting a form with an array of data. Surprisingly, it works perfectly fine when I test it on POSTMAN. Although I attempted to use this form, it did not yield the desired results: ...