Igor Simic
3 years ago

Angular - how to get route param


How to get route params when using Angular routing. I will show how to get query params, but also dynamic params like for example when we want to query posts by tag and URL will look like this: post/tag/:slug   - where slug can have different values - for example post/tag/angular, or post/tag/javascript.

First thing first, let's create our route using angular routing. In our routing module we will have something like this:
...
{
  path: 'post/tag/:slug',
  component: PostTagComponent,

}
...

Now in our PostTagComponent we will include ActivateRoute
import {ActivatedRoute} from "@angular/router";
...
constructor(
  private route: ActivatedRoute,
) { }
by using ActivatedRoute we can easily grab our route param. If our route is like this post/wall/angular  we can use route.snapshot :
ngOnInit() {

   console.log(this.route.snapshot.params); // outputs: {slug: "angular"}
   console.log(this.route.snapshot.params.slug); // outputs angular

   // or we can use get method
   console.log(this.route.snapshot.paramMap.get("slug")); // outputs angular

}
We can also use route params subscription to get these values:
this.route.params.subscribe((data:any)=>{
    console.log(data); // outputs: {slug: "angular"}
  }
)


If we have a route with query params, like this: post/wall/angular?test=one&test2=two in this case we will use queryParams 
console.log(this.route.snapshot.queryParamMap.params); // outputs {test: "one", test2: "two"}
console.log(this.route.snapshot.queryParamMap.keys);  // outputs ["test", "test2"]
console.log(this.route.snapshot.queryParamMap.get('test')); // outputs "one"


or we can use queryParam subscription
this.route.queryParams.subscribe(params=>{
      console.log("params");
      console.log(params); // outputs: {test: "one", test2: "two"}

    });

And that would be it.  
Have a nice and productive day!
Godspeed.