Update the router URL without switching pages, yet still record it in the browser history

One of the features on my search page allows users to perform searches and view results.

Initially, I faced a challenge in updating the router URL without navigating, but I managed to overcome this by utilizing the "Location" feature.

In my ngOnInit method - as my search page can be accessed from another page, I have set up a listener for query parameters so that a search can be triggered if any are present:

ngOnInit() {    
    this.queryParamsSubscription = this.activatedRoute.queryParams.subscribe(queryParams => {
      this.searchText = queryParams[TD_QUERY_PARAMS.text];
      if (this.searchText) {
        this.search();
      }
    });
  }

The search method is defined as follows:

search() {    
    const queryParams: Params = { text: this.searchText };
    const desiredUrl = this.router.createUrlTree([], {
      queryParams: queryParams,
      relativeTo: this.activatedRoute,
      skipLocationChange: true
    });
    this.location.replaceState(desiredUrl.toString());
  }

This approach ensures that the URL is updated when a user performs a search within the search page, covering the first part of my solution.

However, I also aim to include each search in the browser history, illustrated by the following steps:

  • I initially launch the application at 'localhost:4200/landing'.

  • From the landing page, I use the search bar to navigate to the search page.

  • Upon reaching the search page, I search for '1', resulting in navigation to: 'localhost:4200/search?text=1'

  • Subsequently, I conduct a search for '2' on the search page, which updates the URL to: 'localhost:4200/search?text=2'

  • Lastly, I perform a search for '3', leading to the URL: ''localhost:4200/search?text=3'.

When attempting to go back using the browser's 'Back' button, the expected behavior would be to return to 'localhost:4200/search?text=2'. Unfortunately, none of the searches made on the page are recorded in the history. As a result, the navigation reverts to the previous page, 'localhost:4200/landing'.

Any suggestions on how I can add these searches to the browser's history?

Answer №1

I think one of these options might be helpful for you:

  1. this.router.navigate(['/yourRouteGoesHere'], { replaceUrl: true });

  2. Alternatively, you could consider using: SkipLocationChange

    this.router.navigateByUrl(['yourFullPath'], { skipLocationChange: true });

  3. Another option is to utilize this.router.replaceUrl('path').

This approach allows you to navigate without recording this route in the history.

Answer №2

I discovered that I was overanalyzing the problem at hand.

Simply by implementing

router.navigate(['/search'], { queryParams: queryPrams })

I achieved the desired outcome. The URL was updated, and a new entry was made in the browser history.

I overlooked the fact that router.navigate does not trigger a full page reload when only the queryParams are modified.

Hopefully, this information proves useful to others facing similar challenges.

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

Pair of dimensions painting with d3 version 4

I am having trouble converting my code from d3 v3 to d3 v4 Below is the original code snippet: var brush = d3.svg.brush() .x(x) .y(y) .on("brushstart", brushstart) .on("brush", brushmove) .on("brushend", brushend); However ...

Safari Glitch in Bootstrap 4

For a simplified version, you can check it out here: https://jsfiddle.net/dkmsuhL3/ <html xmlns="http://www.w3.org/1999/xhtml"> <title>Testing Bootstrap Bug</title> <!-- Bootstrap V4 --> <link rel="stylesheet" href="https://m ...

Combining jQuery form validation with a PHP script on a single webpage

After implementing jQuery form validation and redirecting using the function btn_onclick() { window.location.href = "http://localhost/loginprivate.php";} from index.php to loginprivate.php, my web app's PHP script is not being executed. The user is re ...

Change a JavaScript object into an array with different options while still maintaining the keys

I am attempting to transform the following JavaScript object: image_uploads: [ 0: { upload_id: 50, }, 1: { upload_id: 51, }, 2: { upload_id: 52, }, ] Into separate entries using this structure for inclusion in the body of a POST r ...

Is there internal access to the "access property" within the "data property" in JavaScript?

I have come to understand that there are two types of properties in objects: data properties and accessor properties. It is possible to access the "data property" without using an "accessor property," as shown below: const person = { name: 'Pecan&a ...

Refresh stock value in anychart without having to re-render the entire chart

I am currently experimenting with the Anychart stock candlestick chart and I must say, it is quite impressive. However, I have encountered an issue while trying to update the chart using a setInterval function. The problem is that it re-plots the entire ch ...

Tips for hiding the overflow scrollbar on Microsoft Chrome when there is no content to scroll

Looking for a solution to hide scroll bars in Microsoft Chrome, but only when there is no content to scroll? The current div and styles always show the horizontal and vertical scroll bars, even when the height exceeds the content. <div style="backgroun ...

What causes the data to flicker between the old and new values when the state is updated in ReactJS?

Currently, I am developing a single-page application that fetches data from the Star Wars API. In the character section of the project, the goal is to display characters per page with the ability to navigate to the next or previous pages by clicking on but ...

Exploring the possibilities of Angular 2 with a simple static page

Currently, I am working on an Angular 2 project and I'm trying to open static help files that are available on the server in a new window. I attempted to use window.open(help/index.html), but it navigates to the page and then throws an error about the ...

Angular 8 wild card redirect problem with Routable Modals

I have a Modal that can be routed with unique parameters to display Training content defined in the app-routing.module.ts file { path : 'TopshelfContent/:catName/:cmsID', component: ModalContainerComponent, canActivate: [MsalGuard]}, When manua ...

Is it possible to rearrange the positions of 2 divs using solely CSS?

I have created a unique design. On iPad, I am assigning the class 'handHeld' to the <body>, which will trigger positional changes between optionsWrapper and #container using CSS classes I've defined below on jsfiddle.net. .handHeld d ...

Capturing AJAX responses within a Chrome Extension

We are currently in the process of developing a Chrome extension to enhance an existing system by simplifying various tasks. This extension will heavily utilize AJAX technology, making it more efficient compared to web scraping or manually triggering even ...

Is it possible to use getJSON to retrieve a value from an HTML tag ID that has already been displayed on a webpage? How about using json_decode

Is there a way to retrieve the value using the HTML tag ID after an HTML page has been rendered? For example, how can I access the date value using the td_date in my JavaScript function? Below is the code snippet that populates the data on the page: listS ...

PHP regular expression /only match 10 whole digits/;

Currently, I am working on updating a PHP script that contains the following code snippet: function CheckNumber(MyNumber) { var MN = /^\d{10}$/; if (MN.test(MyNumber)) { return true; } return false; } The current script enfor ...

Choosing an element that does not have a particular string in its colon attribute name

In my code, I have multiple elements structured like this: <g transform="matrix"> <image xlink:href="data:image/png" width="48"> </g> <g transform="matrix"> <image xlink:href="specific" width="48"> </g> <g tran ...

Having trouble detecting the Selection event of a Dropdown List upon loading

When a user chooses an option from the dropdown menu, I need to capture the selected item and perform an action: $("#user-list").on("change", function() { var selectedUser = $(this).find(":selected").text(); // Perform action with the selected us ...

Guide on creating a Meteor Bootstrap WhatsApp clone

I'm currently going through the step-by-step guide for Whatsapp on the following website: After entering this command: meteor npm install angular@^1.5.8 --save I encountered the following message: no matches found: angular@^1.5.8 Does this mean t ...

The Vue template syntax utilizes double curly braces for incrementing values within must

Embarked on learning Vue.js recently and I am intrigued by the unusual behavior in my simple code. I cannot seem to figure out what is going wrong. I am attempting to increment a counter inside mustache syntax, but something strange is happening with this ...

Sending the selected object from a dropdown in React back to its parent component

I have encountered a few issues with my React dropdown component. My main goal is to pass the selected object from the dropdown back to the Parent component. Currently, the dropdown list is functional and I am able to pass {this.state.selectedUser} back to ...

Employing jQuery to add an element as a sibling rather than a child node

I'm having trouble finding the specific functionality I need. My goal is to add sibling DOM elements to a disconnected node. From what I gather, it should be possible with either .after() or .add(), but for some reason both methods are not working as ...