Is there a way to go back to the previous URL in Angular 14?

For instance, suppose I have a URL www.mywebsite.com/a/b/c and I wish to redirect it to www.mywebsite.com/a/b

I attempted using route.navigate(['..']) but it seems to be outdated and does not result in any action.

Answer №1

There is a clever and effective solution available if you prefer to handle this situation properly.

While many responses on this platform suggest using the back() method in the Location service, it's important to note that there is an issue with this approach. If a user opens a new tab, there may not be a history entry to navigate back to. This can potentially disrupt the Angular application and create security vulnerabilities since there is no direct API for examining browser history.

This solution is inspired by a helpful blog post authored by Nils Mehlhorn

Navigation Service

import { Injectable } from '@angular/core'
import { Location } from '@angular/common'
import { Router, NavigationEnd } from '@angular/router'

@Injectable({ providedIn: 'root' })
export class NavigationService {
  private history: string[] = []

  constructor(
    private router: Router,
    private location: Location
  ) {
    // Listen to router events of type NavigationEnd to
    // maintain an app-specific navigation history.
    this.router.events.subscribe((event) => {
      if (event instanceof NavigationEnd) {
        this.history.push(event.urlAfterRedirects);
      }
    })
  }

  /**
   * Control the back navigation.
   */
  back(): void {
    this.history.pop();

    // If there are still entries in the history after removing
    // the current URL from the stack, it's safe to navigate back.
    // Otherwise, default to returning to the application root.
    if (this.history.length > 0) {
      console.log('navigating back')
      this.location.back();
    } else {
      console.log('navigating to /')
      this.router.navigateByUrl('/');
    }
  }

}

Back button directive

import { Directive, HostListener } from '@angular/core';
import { NavigationService } from './navigation.service';

@Directive({
  selector: '[navigateBack]',
})
export class BackButtonDirective {

  constructor(private navigation: NavigationService) {}

  @HostListener('click')
  onClick(): void {
    this.navigation.back();
  }

}

Utilize the directive in HTML

<button navigateBack>
   <mat-icon>arrow_back</mat-icon>Back
</button>

Answer №2

By utilizing angular's Router and ActivatedRoute, you can effectively navigate back from the currently activated route

constructor(private route: ActivatedRoute,private router: Router) {
}

this.router.navigate(['..'], { relativeTo: activatedRoute });

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

Encountering a problem when trying to use event.target.value in an Angular TypeScript application

Here is the code from my app.component.html : <h1>Password Generator</h1> <div> <label>Length</label> </div> <input (input)="onChangeLength($event.target.value)"/> <div> <div> <input ...

Having trouble with ngx-slick-carousel? Need help with managing the next and prev buttons?

I'm facing an issue where the next and prev buttons are not visible on my carousel component, even though they seem to be working properly. When I inspect the elements, I can see that the buttons are there. How can I make them visible? Here is my cod ...

Angular has the feature of a right float button with *ngfor

I've successfully implemented a form using Reactive Forms in Angular. Currently, my form is displayed as follows: <div class="center" appMcard> <form [formGroup]="GroupRMPM_FG"> <div formArrayName="GroupId_Name" *ngFor="let ...

Which event is triggered following the update of all values in reactive forms?

How can I properly emit an event in Angular (v.5 or v.6) after a specific input of a reactive form has been changed? Here are the approaches I have tried: (ngModelChange)="doSomething($event)" (HTML, basic event) (bsValueChange)="doSomething($event) ...

There is no definition for Angular 4 Material stepper tags

After thoroughly studying the Angular Material stepper documentation, I encountered an issue when attempting to integrate the HTML Material stepper tag into my Angular application. The error message stated that it's not a known element. HTML: <ma ...

Configuring price range filtering without the need for an apply button using Angular Material in Angular 6

I need help with implementing a feature where the user can select a starting price and an ending price, and based on that selection, I want to display relevant products without the need for a button. I want to achieve this using mat-slider to sort the prod ...

What is the best way to choose an element within a component's template?

Is there a way to access an element that is defined in a component template? While Polymer has the $ and $$ to make this task simple, I am curious about how it can be done in Angular. Consider the example provided in the tutorial: import {Component} from ...

Obtaining RouteParams in the loader function of RouteConfig can be achieved by following a

Is there a way to achieve the following setup: @RouteConfig([ { path: '/example/:name', name: 'Example', loader: (params: RouteParams) => { let name = params.get('name'); return _EXAM ...

Guide to retrieving specific attributes from an object within an array of objects using Angular Typescript

As an example, if we consider a sample JSON data retrieved from the JSONPlaceholder website at https://jsonplaceholder.typicode.com/users. [ { "id": 1, "name": "Leanne Graham", "username": "Bret&q ...

Instantiate a TypeScript object and establish its type by setting restrictions derived from an input object

I have been working on creating a function that takes an object A: { [key: string]: string | undefined } as its parameter. The goal is to generate a new object B with all properties from A, converting each string property to type number, and each string | ...

Enhancing IntelliSense to recognize exports specified in package.json

I have a package.json file where I define various scripts to be exported using the exports field. "exports": { ".": { "default": "./dist/main.es.js", "require": "./dist/main.cjs.js", ...

Combine all the missing observables in RxJS into a single array

In my code, I am creating a NavBar with items that may require fetching extra information from an API and adding it to the subtitle field. I want to transform this into an Observable<NavItem[]> so that it can be rendered using an Async Pipe. Curren ...

Angular httpClient: Adjusting date format within json object

I need help converting the date property of an object to a format that the server can understand when using httpClient.post(...). Currently, the date property has its natural string representation. What steps can I take to make sure it is in the correct ...

Struggling to compile Angular 8 when using ng2-adsense

I have integrated the ng2-adsense Google Adsense library into my Angular applications to display ads. To set it up, I followed the guidelines provided at this link: https://github.com/scttcper/ng2-adsense/ Include the adsbygoogle.js script in the head s ...

Exploring the capabilities of Angular2 and Jasmine through testing

I have been working on a basic spec for a component and I'm curious about the test's behavior. The test is designed to verify if a component is successfully created. It seems that when the test is executed, it first compiles and runs the Compone ...

How to securely pass or retrieve the referrer page using the GET method in PHP?

After reviewing several discussions regarding redirecting users to the previous page upon login or other actions, it appears that using HTTP_REFERRER to get the previous page URL is considered unreliable and insecure. My query is whether adding extra info ...

Uncovering the Full Scope of a LinkedIn Profile with Typescript

Hello, I am currently in the process of developing an Ionic2 framework app that includes social login functionality. Up to this point, I have successfully integrated Google Plus and Facebook buttons. Now, I would like to add LinkedIn login as well. The c ...

What is the best way to replicate certain key-value pairs in an array of objects?

I am working with an array of objects. resources=[{name:'x', title:'xx',..},{name:'y',title:'yy',..}..] To populate my HTML tooltip, I am pushing all the titles from the resources array to a new array. dialogOkCli ...

Using React with Typescript: What is the best way to implement useMemo for managing a checkbox value?

I am currently developing a to-do list project using React and Typescript. At the moment, I have successfully implemented the functionality to add new to-do items via a form and delete them individually. Each item includes a checkbox with a boolean value. ...

Can we make one tab disappear when another tab is clicked in Ionic 2 app menu icon?

I am working on a project using Ionic 2 and I have implemented multiple tabs in the application. However, I need to find a way to hide the top tab when the user clicks on the bottom tabs menu icon. Here is my Plunker for your reference. My goal is to ma ...