Tips on modifying the URL without disrupting the Angular 5 component

As I venture into the world of Angular2, I am finding it a bit more challenging compared to Angular 1. In Angular 1, it was straightforward to specify {reload: false} to avoid reloading the component while changing the query param in the route. However, I haven't been able to find a similar solution in Angular 2.

In my HTML template, I have a button that changes the query parameter when clicked.

On click of the button, the method updateRoute({type: 'app_dependency'}) is called:


ngOnInit() {
    console.log(`ngOnInit - is called.`);
}
public updateRoute(urlObject) {
    let queryParams = this.activatedRoute.snapshot.queryParams;
    let updatedQuery = clone(queryParams);
    this.activeTab = updatedQuery.type || 'app_dependency';
    forEach(urlObject, (value, key) => {
        updatedQuery[key] = value;
    });
    
    this.router.navigate([], {
        relativeTo: this.activatedRoute,
        queryParams: queryParams
    });
}

Each time this function is called, it destroys the component and calls ngOnInit().

Is there a way to simply change the URL query without reloading the component? If so, any suggestions or help on a better approach would be greatly appreciated.

Answer №1

I stumbled upon the answer right here:
This method will guarantee that the component remains intact.

constructor(
        private router: Router
      ) {
        this.router.routeReuseStrategy.shouldReuseRoute = function () {
          return true;
        };
      }

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

Implementing Observable lambdas in Angular templates for easy function calling

Within a component, I have the following code snippet: public hasFoo$: Observable<(name: string) => boolean> = ... Now, I would like to use this multiple times in my template with a stepper: <mat-vertical-stepper> <mat-step *ngIf="ha ...

The Angular Button fails to display when all input conditions are met

I'm currently working on validating a form using this link. The requirement is simple - when an input field is invalid, the `save` button should be disabled. Conversely, when all input fields are valid, the `SAVE` button should be enabled/shown. The & ...

Issue: Multiplying values within an array in TypeScript requires that the left-hand side of the arithmetic operation must be of type 'any', 'number', or 'enum'

Having trouble with Typescript as I encounter this error message The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.ts(2362) Specifically facing issues when trying to multi ...

Update the TemplateUrl according to the URL Parameters (GET)

I've created a basic Angular code snippet (test.component.ts) that retrieves a variable from GET parameters: import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ select ...

The export enumeration in Typescript-Angular is not defined

I've encountered a strange issue in my Angular project. I have some components and enums set up, and everything was working fine with one component using the enums. But when I tried to implement the same enums in other components, they are returning " ...

ejs-lineargauge major divisions and minor divisions centered

I've been trying to align majorTicks and minorTicks in the middle of the axis, but so far I haven't found a solution despite searching and googling extensively. Here's a snippet of my code: majorTicks: { height: 12, interval: 1, width ...

Ways to set the className prop for all components automatically without having to specify it repeatedly

One challenge I face is dealing with code duplication whenever I create a new component. Is there a way to pass the className property between components without having to explicitly define it every time a new component is created? For example, when I cr ...

The malfunction of Angular's tree component

After installing and importing the Angular tree component, I followed the basic example provided in order to set it up. However, upon following the steps outlined on , I encountered an issue where only the root node is visible without expanding. Could some ...

When is the right time to develop a new component?

Exploring the strategy behind determining when to create a new component in a web application using angularjs / angular has been on my mind lately. It seems like this concept could apply to all component-based front end frameworks as well. I understand th ...

Is there a way to set a default value for a placeholder or tabstop that is equal to the value of a previous placeholder or tabstop

Looking to create a TypeScript import snippet that is simple and efficient, like this: import * as module from 'module'; I want to maintain the as part as the same as the module name. The following template works well for me: "import * as ${1} ...

Choosing a beginning date with the Angular Material Date Picker utilizing a pre-loaded value from a service injection

I am facing an issue with a material DatePicker and form setup in HTML. Here is the abbreviated code: <form novalidate (ngsubmit)="submit" [formGroup]="moneyForm"> <mat-form-field> <input matInput [matDatepicker]="datePicker" ...

Discover the steps to activate and utilize mat-error without the need for form control manipulation

Have you encountered an issue with using ngModel and mat-error without a form? Is there a workaround that allows the use of mat-error with ngModel? #code <mat-form-field appearance="fill" class="w-48per"> <mat-label>Fi ...

The issue of keypress events failing to register in the Quill Inline blot has surfaced

I created a custom Inline Blot in my Quill editor that I want to use to listen for the keypress event on nodes. However, I am facing a problem where the keypress event is never fired, even though the click event works perfectly fine. Below is the code sni ...

Tips for adding temporary text in filter input of Kendo UI Grid using Angular

I'm currently working with Kendo UI Grid in conjunction with Angular, and I am struggling to find a solution for adding text or a placeholder in filter inputs using Typescript. Within my code, I am utilizing the kendoGridFilterCellTemplate: <kend ...

Best practices for interfaces in Typescript

Here's a question that doesn't have a clear-cut answer. I understand that coding styles vary greatly, especially among different languages - for example, camel case function names in JavaScript vs pascal casing methods in C#. I can definitely acc ...

Trouble with Fetch API: PUT request for JSON results in 404 error, even though GET request is functioning

I have a JSON file with the following data: { "clicks": 0 } My goal is to retrieve the information from this file and then update it. While I am able to successfully perform a GET request, the PUT request does not seem to work as expected. I am ...

How can I detect if a control value has been changed in a FormGroup within Angular 2? Are there any specific properties to look

I am working with a FormGroup that contains 15 editable items, including textboxes and dropdowns. I am looking to identify whether the user has made any edits to these items. Is there a specific property or method I can use to check if the value of any i ...

Tips for populating the header of an angular-material card

I am working with an angular-material classic card that has the following template: <mat-card class="example-card"> <mat-card-header> <mat-card-title>Shiba Inu</mat-card-title> </mat-card-header> <mat-card-conten ...

Having trouble accessing a JSON object with Typescript in an Angular 2 project

Something strange is happening with my code. I am working with a JSON object: {"login":"admin","name":"Admin"} And this is the relevant part of my code: private _userData: User; ... private getUserData() { this._userInfoService.getUserInfo() ...

At what exact moment is the APP_INITIALIZER executed?

Incorporated within the app component is the name of the environment like so: <app-component env="dev" /> I require retrieving some configuration from the backend based on this attribute within the app-component. This configuration needs t ...