How to use Angular Router State?

The Angular Router supports passing custom state information with every navigation. Here is an example of using routerLink with some attached state:

As you can see, state is an @Input of the routerLink directive. You can pass any number of objects you want to that state. Such a state gets added to the browser’s history.state object, which can be helpful if you need to pass some information to a non-Angular library, for instance.

The receiving component can access the data using router.getCurrentNavigation(). The state data is then nested under extras.state:

You can find an example in action here on Stackblitz. The example is an app with a list of products. Clicking on a product opens a product details component. The selected product is passed to such component using router state instead of using a resolver and URL parameters, which leaves our router config lightweight:

The end result looks like this:

Alain Chautard

Alain is a Google Developer Expert in Web Technologies, Angular, and Google Maps. His daily mission is to help development teams adopt Angular and build at scale with the framework. He has taught Angular on all six continents! A world traveler and photographer, Alain is also an international conference speaker, and a published author of several video courses.