Introduction

When dealing with routes, one might need to pass data to a route. There are two types of data that can be passed: static and dynamic. In this blog post, I will show you how to pass both types to your route.

Passing static data

In order to pass static data to a route, we use the data property, which allows us to store key/value pair data that is read only and pass it to a route like so:

{
 path: 'stores/abc', 
 component: StoreComponent, 
 data: {
    company: 'ABC',
    storeNumber: 1234,
    url: 'https://www.abcstore.com',    
 }
}

This data can then be accessed in the component using the ActivatedRoute service like this:

“Static Params Component”

Passing dynamic data

In order to pass dynamic data to a route, Angular uses the state object. This object uses the History API in order to store the dynamic data contained within.

We can use a directive called routerLink:

<a [routerLink]="['companies/abc/']" [state]="{id: 1, company: 'ABC',
    storeNumber: 1234,
    url: 'https://www.abcstore.com'}">ABC Company
</a>

Another way is to use navigateByUrl:

this.router.navigateByUrl('/companies/abc', {state: {id: 2, company: 'ABC',
storeNumber: 1234,
url: 'https://www.abcstore.com'}">ABC Company }});

Scalar values cannot be used since the router will automatically add a property called, navigationId.

In order to get the value of the state we use the getCurrentNavigation method that is part of the router. This can only be done inside a constructor like so:

export class CompaniesComponent implements OnInit {

   public routeData: any;

   constructor(private router: Router, private activatedRoute: ActivatedRoute) {

      this.routeData = this.router.getCurrentNavigation().extras.state;
   }  

}

You can also use this.router.navigate:

this.router.navigate(['/companies', {companies: this.companies}]);

You can access it by using the activatedRouteSnapShot like so:

this.activatedRouteSnapshot.data['companies'];

Another way is to use the History API in the ngOnInit:

export class CompaniesComponent implements OnInit {

   public routeData: any;

   ngOnInit() {
      this.routeData = this.location.getState();
   }
}

Conclusion

In this blog post I have covered ways of passing data to routes statically and dynamically. I will be discussing other ways in a future blog post. Thanks for reading and stay tuned!