398

Is there anyway to send data as parameter with router.navigate? I mean, something like this example, as you can see the route has a data parameter, but doing this it's not working:

this.router.navigate(["heroes"], {some-data: "othrData"})

because some-data is not a valid parameter. How can I do that? I don't want to send the parameter with queryParams.

Jota.Toledo
28.6k11 gold badges66 silver badges76 bronze badges
asked Jul 1, 2017 at 18:48
3
  • I think it should be other way like in AngularJS, where we were able to do something like $state.go('heroes', {some-data: "otherData"}) Commented Jul 1, 2017 at 18:55
  • Use my approach npmjs.com/package/ngx-navigation-with-data last comment by me, best for everyone Commented Nov 28, 2018 at 6:23
  • 2
    Routing is a complex feature in Angular and definitely worth learning! Here you may find interesting details about passing data via the routing: indepth.dev/tutorials/angular/… This guide goes through various techniques about using static data in routing definition and dynamic data (state) during specific navigation. Commented Jul 23, 2022 at 11:47

9 Answers 9

924

There is a lot of confusion on this topic because there are so many different ways to do it.

Here are the appropriate types used in the following screen shots:

private route: ActivatedRoute
private router: Router

1) Required Routing Parameters:

enter image description here

2) Route Optional Parameters:

enter image description here

3) Route Query Parameters:

enter image description here

4) You can use a service to pass data from one component to another without using route parameters at all.

For an example see: https://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/

I have a plunker of this here: https://plnkr.co/edit/KT4JLmpcwGBM2xdZQeI9?p=preview

Nasta
9398 silver badges22 bronze badges
answered Jul 1, 2017 at 22:11
Sign up to request clarification or add additional context in comments.

26 Comments

thank you for your answer! What is the difference between the 2) and the 3)? Because both end up adding "?parameter=" in the URL. Could you give me an example for the 4)? I can't figure out how to do it.
I updated by answer to show the different URLs and to provide a link to a blog post and plunker on how to pass data with a service. The URL is different with optional and query parameters as shown above. Plus query parameters can be retained across routes.
I also have a Pluralsight course on routing that covers all of this: app.pluralsight.com/library/courses/angular-routing/… You can sign up for a free week if you are interested in more information.
The data is only "shared" within the executing application. If the user refreshes the page, the entire application is reloaded from the server, so no prior state is retained in the application. Thinking about it in terms of a normal application, when a user refreshes it is like closing and reopening the application. If you need to retain state after a refresh, then you will need to store it somewhere such as local storage or on the server.
Just a small hint: route type is ActivatedRoute, not Router.
|
522

There is a new method what came with Angular 7.2.0

https://angular.io/api/router/NavigationExtras#state

Send:

 this.router.navigate(['action-selection'], { state: { example: 'bar' } });

Receive:

 constructor(private router: Router) {
 console.log(this.router.getCurrentNavigation().extras.state.example); // should log out 'bar'
 }

You can find some additional info here:

https://github.com/angular/angular/pull/27198

The link above contains this example which can be useful: https://stackblitz.com/edit/angular-bupuzn

Akash Kumar Verma
3,3582 gold badges19 silver badges33 bronze badges
answered Jan 25, 2019 at 12:10

14 Comments

This is the correct answer given the new features in Angular 7.
With this approach, how would I handle a browser refresh by the user? In that case the data in the navigation extras seems to go away, so there is no chance to use it again on refresh.
Yep that is why you only can get the data from the this.router.getCurrentNavigation() in the constructor. If you need it elsewhere like inside ngOnInit() you can access the data trough "history.state". From the documentation: "State passed to any navigation. This value will be accessible through the extras object returned from router.getCurrentNavigation() while a navigation is executing. Once a navigation completes, this value will be written to history.state when the location.go or location.replaceState method is called before activating of this route."
Also make sure you don't try to recieve an extras object in ngOnInit() as this.router.getCurrentNavigation().extras
@KinleyChristian Check out this answer, if you have further questions let me know! stackoverflow.com/a/54891361/4222504
|
79

Latest version of angular (7.2 +) now has the option to pass additional information using NavigationExtras.

Home component

import {
 Router,
 NavigationExtras
} from '@angular/router';
const navigationExtras: NavigationExtras = {
 state: {
 transd: 'TRANS001',
 workQueue: false,
 services: 10,
 code: '003'
 }
};
this.router.navigate(['newComponent'], navigationExtras);

newComponent

test: string;
constructor(private router: Router) {
 const navigation = this.router.getCurrentNavigation();
 const state = navigation.extras.state as {
 transId: string,
 workQueue: boolean,
 services: number,
 code: string
 };
 this.test = "Transaction Key:" + state.transId + "<br /> Configured:" + state.workQueue + "<br /> Services:" + state.services + "<br /> Code: " + state.code;
}

Output

enter image description here

Hope this would help!

answered Mar 14, 2019 at 11:31

6 Comments

I keep getting "navigation is null". I have tried several examples...
This is old, but for future visitors – you have to call it inside the constructor. stackoverflow.com/a/54891361/2950032
Can you still access the state data after a page refresh?
ok I just tested this myself, and it works perfectly only directly after routing to the new component from the old one. Once you reload the page, the state is undefined : (
This works perfectly till the user reload the page. Then state will be undefined. :(
|
11

I needed access to the data in CustomRouteReuseStrategy and I couldn't inject the Router there due to a circular dependency but you can use the Location object to read the state as well.

Send:
 this.router.navigate(['action-selection'], { state: { example: 'bar' } });
Receive:
 import { Location } from '@angular/common';
 constructor(private location: Location) {
 console.log(this.location.getState().example); // should log out 'bar'
 }
answered Mar 7, 2022 at 20:11

2 Comments

This way works well. If you want to use it entirely in the template, provide your state as bound input to the same element you're providing routerLink to. Eg: <button [routerLink]="['action-selection']" [state]="{ example: 'bar' }"> Navigate with State </button>
This worked for me! I just had to use: console.log((this.location.getState() as { example: any })?.['example']);
8

Since Angular 15, this.router.getCurrentNavigation() might return null, because the component is instantiated after the navigation.

The alternative is to access the state from the Location (the one from @angular/common)

 import { Location } from '@angular/common';
 constructor(private location: Location) {
 location.getState() // do what you want 
 }
answered Jan 17, 2023 at 18:08

2 Comments

2

In navigateExtra we can pass only some specific name as argument otherwise it showing error like below: For Ex- Here I want to pass customer key in router navigate and I pass like this-

this.Router.navigate(['componentname'],{cuskey: {customerkey:response.key}});

but it showing some error like below:

Argument of type '{ cuskey: { customerkey: any; }; }' is not assignable to parameter of type 'NavigationExtras'.
 Object literal may only specify known properties, and 'cuskey' does not exist in type 'NavigationExt## Heading ##ras'

.

Solution: we have to write like this:

this.Router.navigate(['componentname'],{state: {customerkey:response.key}});
Yucel Bayram
1,6633 gold badges22 silver badges41 bronze badges
answered Dec 26, 2019 at 11:41

Comments

1

@dev-nish Your code works with little tweaks in them. make the

const navigationExtras: NavigationExtras = {
 state: {
 transd: 'TRANS001',
 workQueue: false,
 services: 10,
 code: '003'
 }
};

into

let navigationExtras: NavigationExtras = {
 state: {
 transd: '',
 workQueue: ,
 services: ,
 code: ''
 }
};

then if you want to specifically sent a type of data, for example, JSON as a result of a form fill you can send the data in the same way as explained before.

answered Apr 11, 2019 at 9:33

Comments

0
getStateById(stateId) {
 return this.http.get<any>(environment.user_service_url + "/getStateById",
 {params:{"stateId": stateId}});
 }
MD Ashik
9,89310 gold badges56 silver badges61 bronze badges
answered Jul 12, 2022 at 2:57

Comments

-14

Best I found on internet for this is ngx-navigation-with-data. It is very simple and good for navigation the data from one component to another component. You have to just import the component class and use it in very simple way. Suppose you have home and about component and want to send data then

HOME COMPONENT

import { Component, OnInit } from '@angular/core';
import { NgxNavigationWithDataComponent } from 'ngx-navigation-with-data';
@Component({
 selector: 'app-home',
 templateUrl: './home.component.html',
 styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(public navCtrl: NgxNavigationWithDataComponent) { }
 ngOnInit() {
 }
 navigateToABout() {
 this.navCtrl.navigate('about', {name:"virendta"});
 }
}

ABOUT COMPONENT

import { Component, OnInit } from '@angular/core';
import { NgxNavigationWithDataComponent } from 'ngx-navigation-with-data';
@Component({
 selector: 'app-about',
 templateUrl: './about.component.html',
 styleUrls: ['./about.component.css']
})
export class AboutComponent implements OnInit {
 constructor(public navCtrl: NgxNavigationWithDataComponent) {
 console.log(this.navCtrl.get('name')); // it will console Virendra
 console.log(this.navCtrl.data); // it will console whole data object here
 }
 ngOnInit() {
 }
}

For any query follow https://www.npmjs.com/package/ngx-navigation-with-data

Comment down for help.

answered Nov 28, 2018 at 6:20

4 Comments

Does it transfer data in the form of params or just in the background?
I couldn't understand @MariumMalik Can you please ask in a descriptive way?
Yes it does @MariumMalik
You appear to be the author of this, rather than "I found on the internet"? You are also being asked not to spam it on the Angular 7 thread that implements similar functionality (github.com/angular/angular/pull/27198)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.