Angular ActivatedRoute Example
March 11, 2024
On this page we will learn to use ActivatedRoute
class in our Angular router application.
1.
ActivatedRoute
contains the route information of a component loaded in router outlet. It is used to traverse the RouterState
tree and extract information from nodes.
2.
ActivatedRoute
contains the properties to fetch information about a route associated with the component loaded in the outlet. The properties of ActivatedRoute
are snapshot, title, url, params, queryParams, fragment, data, outlet, component, routeConfig, root, parent, firstChild, children, pathFromRoot, paramMap, queryParamMap.
3. To get array of URL segments, use
url
property that gives an array of UrlSegment
.
4. To get information of path parameters of route, use
params
and paramMap
.
5. To get information of query parameters of URL, use
queryParams
and queryParamMap
.
6. To get hash fragment of the URL, use
fragment
property.
7. To get information about children routes, use
firstChild
and children
properties.
8. To get current snapshot of the route, use
snapshot
property.
9. The instance of
ActivatedRoute
can be obtained by dependency injection in a component.
constructor(private route: ActivatedRoute) { }
ActivatedRoute
is imported from @angular/router
.
Contents
1. snapshot
ActivatedRoute.snapshot
gives current snapshot of this route. snapshot
is the instance of ActivatedRouteSnapshot
class. The ActivatedRouteSnapshot
contains route information of a component loaded in outlet at a particular moment in time. ActivatedRouteSnapshot
is the snapshot of ActivatedRoute
at a particular moment in time. The properties of ActivatedRouteSnapshot
are title, url, params, queryParams, fragment, data, outlet, component, routeConfig, root, parent, firstChild, children, pathFromRoot, paramMap, queryParamMap.
Find the sample code to use
ActivatedRoute.snapshot
.
constructor(private route: ActivatedRoute) { } ngOnInit() { const city: string = this.route.snapshot.params['city']; const url: string = this.route.snapshot.url.join(''); const fragment = this.route.snapshot.fragment; const tracingId = this.route.snapshot.data['tracingId']; }
2. title
ActivatedRoute.title
is an observable that emits title of the route.
Suppose I have following route configuration.
const routes: Routes = [ { path: 'add-customer', component: CustomerComponent, title: "Add Customer" } ]
ActivatedRoute.title
.
constructor(private route: ActivatedRoute) { } ngOnInit() { this.route.title.subscribe(title => { console.log(title); // Output - Add Customer }); }
3. url
ActivatedRoute.url
is an observable that emits array of UrlSegment
matched by this route.
UrlSegment
represents a single URL segment. Its properties are path, parameters, parameterMap.
constructor( private route: ActivatedRoute) { } ngOnInit() { this.route.url.subscribe((urlSegments: UrlSegment[]) => { urlSegments.forEach((segment: UrlSegment) => { console.log(segment.path); console.log(segment.parameters); console.log(segment.parameterMap); }); }); }
4. params and paramMap
1.ActivatedRoute.params
and ActivatedRoute.paramMap
properties are used to access path parameters of the route.
2.
ActivatedRoute.params
is an observable that emits Params
instance on subscribe. Params
contains the path parameters and its values.
3.
ActivatedRoute.paramMap
is an observable that emits ParamMap
instance on subscribe. ParamMap
is a map that provides values of required and optional path parameters of this route. The methods of ParamMap
are has(), get(), and getAll() . We can get all keys as parameter names by using its keys property.
Suppose custCity and custId are path parameters in our route configuration.
const routes: Routes = [ { path: 'customer/:custCity/:custId', component: CustomerComponent } ]
We can fetch the values of custCity and custId using
params
as below.
this.route.params.subscribe(params => { console.log(params['custCity']); console.log(params['custId']); });
In his way we can access path parameters using
params
property. Find the sample code to access path parameters and using them to get customer object in our application.
constructor(private route: ActivatedRoute, private customerService: CustomerService) { } ngOnInit() { this.route.params.pipe( switchMap((params: Params) => this.customerService.getCustomer(params['custCity'], params['custId'])) ).subscribe(customer => console.log(customer)); }
We can fetch the values of custCity and custId using
get()
method of paramMap
as below.
this.route.paramMap.subscribe((map: ParamMap) => { console.log(map.get('custCity')); console.log(map.get('custId')); });
paramMap
.
this.route.paramMap.pipe( switchMap((map: ParamMap) => this.customerService.getCustomer(map.get('custCity'), map.get('custId'))) ).subscribe(customer => console.log(customer));
5. queryParams and queryParamMap
1.ActivatedRoute.queryParams
and ActivatedRoute.queryParamMap
both properties are used to fetch query parameters of the URL.
2.
ActivatedRoute.queryParams
is an observable of Params
.
3.
ActivatedRoute.queryParamMap
is an observable of ParamMap
that contains the query parameters and its values as map.
Suppose I have a router link that creates a URL with query parameters.
<a routerLink="/customer/add" [queryParams]="{custId: 111, custName: 'Vivek'}">Customer</a>
/customer/add?custId=101&custName=Vivek
On subscribing
queryParams
, we can fetch query parameters as below.
this.route.queryParams.subscribe((params: Params) => { console.log(params['custId']); // Output - 111 console.log(params['custName']); // Output - Vivek });
queryParams
. Here we fetch query parameter and pass it to our service.
constructor(private route: ActivatedRoute, private customerService: CustomerService) { } ngOnInit() { this.route.queryParams.pipe( switchMap((params: Params) => this.customerService.addCustomer(params['custId'], params['custName'])) ).subscribe(result => console.log(result)); }
On subscribing
queryParamMap
, we get ParamMap
instance. Using its get()
method, we can fetch query parameters.
this.route.queryParamMap.subscribe((map: ParamMap) => { console.log(map.get('custId')); console.log(map.get('custName')); });
queryParamMap
.
this.route.queryParamMap.pipe( switchMap((map: ParamMap) => this.customerService.addCustomer(map.get('custId'), map.get('custName'))) ).subscribe(result => console.log(result));
6. fragment
ActivatedRoute.fragment
is an observable that emits URL hash fragment as string.
Suppose we have a router link that creates URL with hash fragment.
<a routerLink="/book/page/11" fragment="bottom">Book</a>
/book/page/11#bottom
fragment
to access hash fragment.
this.route.fragment.subscribe(fragment => console.log(fragment));
7. data
ActivatedRoute.data
is an observable that emits instance of Data
on subscribe. Data
represents static data associated with a particular route.
Route.data : We can define our data in route configuration using
data
property of Route
that is accessed by ActivatedRoute.data
property.
const routes: Routes = [ { path: 'customerDetail', component: CustomerDetailComponent, data: {confId: 12, fileName: 'abc.txt'} } ]
ActivatedRoute.data
to access route data defined above.
constructor(private route: ActivatedRoute) { } ngOnInit() { this.route.data.subscribe((data: Data) => { console.log(data['confId']); // Output - 12 console.log(data['fileName']); // Output - abc.txt }); }
8. outlet and component
ActivatedRoute.outlet property gives outlet name of the route.ActivatedRoute.component property gives component name of the route.
const outlet = this.route.outlet; console.log(outlet); const component = this.route.component; console.log(component?.name);
9. routeConfig
ActivatedRoute.routeConfig
gives configuration used to match this route. It contains instance of Route
.
routeConfig: Route | null
Route
information using routeConfig
.
const data = this.route.routeConfig?.data; console.log(data); const path = this.route.routeConfig?.path; console.log(path); const title = this.route.routeConfig?.title; console.log(title);
10. root and parent
ActivatedRoute.root
and ActivatedRoute.parent
both contains the instance of ActivatedRoute
.
The
root
property gives the information of root of router state.
The
parent
property gives the information of the parent of this route in the router state tree.
const root: ActivatedRoute = this.route.root; console.log(root.component); console.log(root.outlet); const parent: ActivatedRoute | null = this.route.parent; console.log(parent?.component); console.log(parent?.outlet);
11. firstChild and children
ActivatedRoute.firstChild : Keeps information of the first child of this route as the instance ofActivatedRoute
.
ActivatedRoute.children : Keeps information of children of this route in router state tree as an array of
ActivatedRoute
instances.
Code snippet for firstChild property.
const firstChild: ActivatedRoute | null = this.route.firstChild; console.log(firstChild?.component); console.log(firstChild?.data);
const children: ActivatedRoute[] = this.route.children; children.forEach((child: ActivatedRoute) => { console.log(child.component); console.log(child.data); });
12. pathFromRoot
ActivatedRoute.pathFromRoot
tracks the routes from root path to this route. It contains an array of ActivatedRoute
instances.
const pathFromRoot: ActivatedRoute[] = this.route.pathFromRoot; pathFromRoot.forEach((path: ActivatedRoute) => { console.log(path.component); console.log(path.outlet); });