Navigating through Dynamic URL Parameters with RouterLink in an Angular Application

Within my Angular 2 application, there exists a tab section where users can choose from a collection of separate yet contextually connected components. By clicking on one of these links, the corresponding component is loaded based on the routerLink definition, as shown here:

<a class="page-content-header-item" routerLink="/page1" routerLinkActive="selected">Page 1</a>

This functionality was functioning smoothly until we implemented a feature that saves user-selected filter options as parameters in the URL. This way, when they revisit the component, their most recent selections are still visible and applied to the data. For instance, the URL may appear like this after a user has set some filters:

http://somesite.com/page1;language_filter=true;language_selection=English

The code snippet for handling this process looks like so:

public changePage(page, value, type, body)
{
    this.onUserSelection(value, type, body, page);

    this.route.params.subscribe(
        (params: any) => {
            this.page = params['page'];
            this.language_filter = params['language_filter'];
            this.language_selection = params['language_selection'];
        }
    );
    this.router.navigate(
        ['/page1', {
            page: page,
            language_filter: this.language_filter,
            language_selection: this.language_selection,
        }]);
}

This approach works effectively for the primary navigation methods which utilize routing files with configurations like this:

{ path: 'page1', component: Page1Component, canActivate: [AuthGuard], data: {contentId: 'page1'} }

However, in the mentioned tab area, components are loaded based on fixed routerLink parameters. Consequently, when a user returns to a component through this method rather than other available pathways, it overrides the URL parameters due to the hardcoded "page1" loading.

Hence, the previously added URL parameters get erased upon reloading.

Therefore, my query is whether it's possible to modify this piece of code:

<a class="page-content-header-item" routerLink="/page1" routerLinkActive="selected">Page 1</a>

...to allow for dynamic variables? Or should I seek an alternative approach to handle navigation within this tab section?

Answer №1

Here is my approach using the queryParams feature.

To begin, you can utilize the queryParams directive within the routerLink directive to pass parameters:

<a routerLink="/page1" [queryParams]="fooParams">Page 1</a>
<a routerLink="/page2">Page 2</a>
<router-outlet></router-outlet>

Here, fooParams represents a simple object:

export class MainComponent {
  fooParams = {
    language_filter: true,
    language_selection: 'english'
  }
}

Angular will generate a URL like

href="localhost:4200/page1?language_filter=true&language_selection=english"

Next, you need to intercept the ActivatedRoute in order to extract parameter values from the ActivatedRouteSnapshot. This can be accomplished through a resolver or directly in your component. In this instance, a resolver is employed:

@Injectable()
export class RoutingResolve implements Resolve<any> {
  resolve(routeSnapshot: ActivatedRouteSnapshot) {
    const { language_filter, language_selection } = routeSnapshot.queryParams;
    return { language_filter, language_selection };
  }
}

Subsequently, include the resolver in the route definition:

const ROUTES: Routes = [
  { 
    path: 'page1',
    component: PageOneComponent,
    // Define a resolver to intercept the activatedRoute snapshot before loading the component
    resolve: {
      routing: RoutingResolve
    }
  },
  { 
    path: 'page2',
    component: PageTwoComponent
  }
];

Within PageOneComponent, subscribe to the resolved data and manipulate it as needed, such as updating form values based on queryParams changes.


For a detailed example, refer to this plunker

Ensure to view the preview in a separate window to observe route changes in the browser.

By navigating to Page 1, modifying form values, switching to Page 2, then returning via browser back button, you'll notice the form reflects the params in the URL.

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

Utilizing the spread operator in Typescript interfaces: best practices

I have a react component that includes the spread operator operating on ...other and passed down to lower levels of the component. interface ButtonProps { colourMode: string; regular: boolean; buttonText: string; disabled?: boolean; iconSize?: st ...

Attempting to display a collection of 16 diverse images by utilizing the Math.random function in conjunction with a

I have been attempting to retrieve 16 random images, but I keep getting duplicates. I am aware that a modification needs to be made to the one => one.number filter, however all attempts so far have been unsuccessful. import React from "react"; import ...

What was the reason for node js not functioning properly on identical paths?

When the search route is placed at the top, everything works fine. However, when it is placed at the end, the route that takes ID as a parameter keeps getting called repeatedly in Node. Why does this happen and how can it be resolved? router.get('/se ...

Is there a way to restrict the return type of a function property depending on the boolean value of another property?

I'm interested in creating a structure similar to IA<T> as shown below: interface IA<T> { f: () => T | number; x: boolean } However, I want f to return a number when x is true, and a T when x is false. Is this feasible? My attempt ...

How can you utilize Angular 2 Services for sharing global variables?

Within our NG starter boilerplate, the file app.component.ts contains the following code: export class AppComponent {title = "Website Title"} The title variable will be displayed in the appropriate app.component.html as shown below: <p>{{title}}&l ...

In VueJS, the v-for directive allows you to access both parameters and the event object within

Imagine having nested elements that repeat using v-for in the following structure: <div id="container"> <div v-for="i in 3"> <div v-for="j in 3" v-on:click="clicked(i,j)"> {{i+&a ...

Enlarge the div with a click

I was looking for a solution on how to make a div expand when clicked using jQuery I came across a tutorial that seemed simple and perfect, but I couldn't get it to work when I tried to replicate the code. Do you know if this code is still valid wit ...

Fade in an image using Javascript when a specific value is reached

Here's the select option I'm working with: <div class="okreci_select"> <select onchange="changeImage(this)" id="selectid"> <option value="samsung">Samsung</option> <option value="apple">App ...

The timing of the JavaScript dialog with the AJAX call is off-kilter

Encountering an issue with a JavaScript script designed to showcase a JQUERY dialog box based on a C# ViewModel. Within a repeater, there is an ASP drop-down menu displaying 'Registration Date' details. The objective is for the JavaScript dialog ...

Dealing with nullable objects in Typescript: Best practices

Looking for a solution to have a function return an object or null. This is how I am currently addressing it: export interface MyObject { id: string } function test(id) : MyObject | null { if (!id) { return null; } return { ...

Vue-ctl project creation halted by operating system rejection

While working on a Vue-CLI project, I encountered an issue. Has anyone else faced this problem before? Operating system: Windows 10 - Command Prompt (admin rights) @vue-cli version: 4.5.4 npm version: 6.14.6 Here is the command I ran: vue create font_ ...

The scale line on the OpenLayers map displays the same metrics twice, even when the zoom level is different

When using the Openlayers Map scale line in Metric units, a specific zoom rate may be repeated twice during the zoom event, even though the actual zoom-in resolution varies on the map. In the provided link, you can observe that the zoom rates of 5km and ...

What methods can be used to accomplish this effect using CSS and/or Javascript?

Is there a way to achieve the desired effect using just a single line of text and CSS, instead of multiple heading tags and a CSS class like shown in the image below? Current Code : <h2 class="heading">Hi guys, How can i achieve this effect using j ...

Angular Space-Friendly Table

After attempting to code the sample in Angular, I realized it wasn't what I was looking for. <table> <th >Number</th> <th >Merchant Name</th> ...

What is the best way to depict object key replacements within a Typescript definition?

I currently have these types: type PossibleKeys = number | string | symbol; type ValueOf<T extends object> = T[keyof T]; type ReplaceKeys<T extends Record<PossibleKeys, any>, U extends Partial<Record<keyof T, PossibleKeys>> = ...

Challenge encountered while populating dropdown in Angular reactive form

When using template-driven forms, I was able to populate dropdowns. However, now that I'm using material reactive form, I am unable to do so. My goal is to populate the "country" dropdown and then call an "onstatechange" event later on to populate the ...

Efficient Error Handling in Next.JS with Apollo GraphQL Client

Although the component successfully renders the error state, an uncaught exception is displayed in the console and a dialogue box appears in the browser. How can expected errors be handled to prevent this behavior? import { useMutation, gql } from "@a ...

Is there a method to generate an endless carousel effect?

Hello, I am trying to create an infinite carousel effect for my images. Currently, I have a method that involves restarting the image carousel when it reaches the end by using the code snippet progress = (progress <= 0) ? 100 : 0;. However, I don't ...

Is it possible to reset the text within the text box when the form is being submitted using the load() ajax function?

I am working on implementing a comment feature where the data entered in the form is appended and displayed after submission. Here is my HTML form: <table> <tr><td>Name :</td><td> <input type="text" id="name"/></td&g ...

Tips for retrieving the value sent via an AJAX $.post request in a PHP file

Here is an example of my Ajax call: var keyword = $('#keyword').value; $.post("ajax.php?for=result", {suggest: "keyword="+keyword}, function(result){ $("#search_result").html(result); }); In the PHP file, I am trying to ret ...