Hot off the Press: Passing Data between Routes in Angular v7.2
For any folks that might have missed it, Angular now supports passing arbitrary data
via a state
object during navigation 😍.
The feature was requested mid-2016, but has just been merged as part of the Angular 7.2 release.
Setting the State
First off, the state must be an object. The Router will add a navigationId
property to it during the navigation, so passing a scalar value will not work.
With that out of the way, you can set the state in two ways:
- Imperative navigation using the
router.navigateByUrl()
method, passing astate
object:
2. Declarative navigation using the routerLink
directive, passing a state
input:
Reading the State
Now that we know how to pass a state
object let’s take a look at how to retrieve it. We can do that in two ways:
1. Read it from the window.history.state
property after the navigation has finished. You can use it to read the state from inside the component that you are navigating to.
2. Read it from the NavigationExtras
property of the NavigationStart
event. This one is useful in top level components, because you cannot listen to the NavigationStart
event from inside the component that you are navigating to.
If you’d like to learn more about the changes, head out to the PR that brings in this change.