Sharing items while navigating through the router

Is there a better way to pass objects when navigating to a target component using Angular router? Currently, I am using routeParams and stringifying my objects, but I'm not satisfied with this approach. What would an improved solution entail?

export class Overview {
    //import {Router} from "@angular/router-deprecated";
    constructor(private router:Router) {}
    goToElementComponent(elem:Element) {
        this.router.navigate(['ElementDetail', {elem: JSON.stringify(elem)}]);
    }
}
export class ElementDetail {
    // import {RouteParams, Router} from "@angular/router-deprecated";
    this.elem : Element;

    constructor(private routeParams:RouteParams) {}

    ngOnInit() {
        var elem = JSON.parse(this.routeParams.get("elem"));
        if (elem) {
          this.elem = elem;
        } else {
          this.elem = new Element();
        }
    }
} 

Answer №1

//Please note: router:Router and route:ActivatedRoute
//Sending an object from one component (with its independent parent-child relationship with another component): 
  billDetails = {
    'customerName': "RAJESH",
    'billNo': "A230",
    'date': "23/12/2020",
    'address': "AGRA",
    'itemDetails':"HUSQVANA VITIPILEN",
    'grandTotal': 2500000
  }
this.router.navigate(['/billingpdf',{billingInfo:JSON.stringify(this.billDetails)}])

//To access this object in another component, you can do the following:
//-------------------------------------------------------
this.route.snapshot.paramMap.get('billingInfo') //store this variable for further use
                                    or
this.route.snapshot.paramMap.getAll('billingInfo')

Answer №2

One alternative method is to save the temporary parameters in a Shared Service

To access your object's parameters, you'll need to include the service in constructors

Answer №3

If you want to pass custom data while navigating in Angular, you can achieve it using the NavigationExtras parameter of the navigate method. Simply create a NavigationExtras object with a state parameter where you can define your custom data:

this.router.navigate(['/route-to'], {
      state: {
        someData: { name: 'Some name', description: 'Some description' },
      },
    });

In the component that is being navigated to, you can access this data like so:

constructor(private router: Router) {
 this.dataFromRoute = this.router.getCurrentNavigation().extras.state?.['someData'];
}

Answer №4

To pass an object in the queryParams, use this syntax:

this.router.navigate(['/my-route'], {queryParams: myObject});

Answer №5

Check out the link at for a solution on how to achieve this in JavaScript.

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

Blending i18n JIT and AOT in Angular 6

Currently, it appears that the development environment is utilizing Just-In-Time (JIT) compilation while production is using Ahead-Of-Time (AOT) compilation, which is expected behavior. However, an issue arises when attempting to retrieve the LOCALE_ID in ...

Angular fixes corrupted Excel files

My current project involves using Angular to call an API and retrieve a byte[] of an Excel file. However, I am facing issues with the file becoming corrupted when I convert the byte[] to a file using blob. Can anyone offer assistance with this problem? M ...

Draggable element on Angular sidenav slides underneath mat-sidenav-content when dragged

I'm currently working on a project where I need to drag a picture from the mat-sidenav and drop it into the mat-sidenav-content area with the copy function. My initial approach was to simply add the drag functionality to a div element in the sidenav, ...

Having some trouble getting @angular/cli to install properly on my Ubuntu system

After numerous attempts to install @angular/cli on Ubuntu terminal, I kept encountering the following error: **npm ERR! 404 Not Found: @angular/cli@latest**. Even though I had installed nodejs with nvm and set NVM_BIN path to /root/.nvm/versions/node/v9. ...

Get the latest B2B department for the client within Spartacus

How can I display the current B2B Unit name in the header for the customer? I have been exploring ways to retrieve the B2B Unit for the current customer and found that there is a payload available for the /current? endpoint that loads on the initial page ...

Tips for implementing Peer.js in Next.js using TypeScript?

Next.js has the ability to run on the server side, which can result in Peer.js throwing errors when used with Next.js. One user on Stack Overflow explains this issue: The error is likely due to peer js performing side effects during import. The suggest ...

A bespoke Typescript implementation of nested lists containing numbers

Currently, I am trying to figure out how to declare and populate a TypeScript list of lists. The structure of the list should be as follows: List<CustomList<>, number> Typically, I would create a standard list like this: someList: { text: a ...

Guide to invoking a REST API endpoint in TypeScript and retrieving the data it returns

In my React SPFx web part, I'm trying to retrieve the current SharePoint Page Title using this API Call: let listTitle: string = this.props.context.pageContext.list.title; let pageItemId: number = this.props.context.pageContext.listItem.id; let url = ...

Steps for initiating a download for an Angular Progressive Web App

In the process of building an Angular PWA, I am interested in finding a method to display a popup notification for users who are browsing my app, prompting them to add it to their home screen. Is there a way to achieve this? ...

On the subsequent iteration of the function, transfer a variable from the end of the function to the beginning within the same

Can a variable that is set at the end of a function be sent back to the same function in order to be used at the beginning of the next run? Function function1 { If(val1.id == 5){ Console.log(val1.id val1.name) } else{} Val1.id = 5 Val1.name = 'nam ...

Unexpected behavior with onKeyPress in React-Native Windows resulting in missing key press events

Currently, I am working on a Windows app using react-native version 0.54.0. For one of the functionalities, I have incorporated a TextInput element and would like to use onKeyPress. Here is my code snippet: <TextInput ref = { this.setTextInputRef } on ...

Node.js is having trouble locating a specific folder module within the local directory

My Typescript and NodeJS Visual Studio project compiles successfully, but I encounter a node runtime error regarding the inability to locate a local module. This is the specific error message: https://i.sstatic.net/6ydxj.png I find it perplexing that th ...

Having trouble setting a default value within an Angular component using ControlValueAccessor?

Demo: https://plnkr.co/edit/cMu3lI3PkxHRErJE3T93?p=preview I've encountered an issue with setting default values for ngModel or formControlName when using ControlValueAccessor in multiple components. For instance, in the provided demo, there is a se ...

Sending Angular forms to various endpoints

On a page, I have a form consisting of three different groups this.form = this.formBuilder.group({ profile: this.formBuilder.group({ name: [''], description: [''], }), members: this.formBuilder.array([ this.formBu ...

The function for utilizing useState with a callback is throwing an error stating "Type does not have

Currently, I am implementing the use of useState with a callback function: interface Props { label: string; key: string; } const [state, setState] = useState<Props[]>([]); setState((prev: Props[]) => [...pr ...

What is the best way to populate empty dates within an array of objects using TypeScript or JavaScript?

I am trying to populate this object with dates from today until the next 7 days. Below is my initial object: let obj = { "sessions": [{ "date": "15-05-2021" }, { "date": "16-05-2021" }, { "date": "18-05-2021" }] } The desired ...

How to automatically close an Angular 2 material dialog

Using angular2 material's MdDialog, I have implemented a form display feature. Upon form submission, a request is made to the backend. If the request is successful, I need to automatically close the dialog. However, if the backend request fails, the ...

creating a custom type with enums in Angular can lead to implicit 'any' issues

Why does the key of [type] require a type? It may sound strange, but I am facing an issue. Here is some example data: export enum ENUM_Bike { suzuki = 'suzuki', yamaha = 'yamaha', kawasaki = 'kawasaki' } export type T ...

Refreshing the parent component when the modal component is closed

I have a component that displays rows from a database in a table. This component includes an "Add" button. When the "Add" button is clicked, a modal pops up with a form to insert a new entry into the database. While I am able to save the new row to the d ...

Effective methods for transmitting reactive form control between child and parent components in Angular 2

I am working with a nested reactive form structure and I have the following setup: Parent HTML Code <form> <child-component></child-component> <button mat-raised-button color="primary">Save</button> </form> Child HT ...