How to get current route in angular

How to get current route in angular

Here is a complete guide to understand how to get current route in angular.

To get the current route in Angular, you can use the Router service provided by the @angular/router module. The Router service allows you to access and interact with the current route information.

Here’s how you can obtain the current route:

Import the necessary modules and inject the Router service into your component:

import { Router } from '@angular/router';
import { ActivatedRoute } from '@angular/router';

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

To get the current route’s URL, you can use the url property of the Router service:

const currentUrl = this.router.url;

The url property returns the current route URL as a string.

To get the current route’s path, you can use the snapshot property of the ActivatedRoute service:

const currentPath = this.activatedRoute.snapshot.routeConfig.path;

The snapshot property provides access to the current route’s configuration, and the routeConfig property contains information about the route, including the path.

Note that when accessing the current route using snapshot, it returns the initial route information when the component is first loaded. If you need to continuously monitor changes to the route, you can subscribe to the paramMap or queryParamMap observables of the ActivatedRoute service:

this.activatedRoute.paramMap.subscribe(params => {
console.log(params.get('id')); // Access route parameters

this.activatedRoute.queryParamMap.subscribe(params => {
console.log(params.get('filter')); // Access query parameters

In the above example, the paramMap and queryParamMap observables allow you to access and handle route parameters and query parameters respectively. By subscribing to these observables, you can stay updated with any changes to the route.

Remember to import the necessary modules (Router, ActivatedRoute) from @angular/router in your component file.

By utilizing the Router and ActivatedRoute services, you can easily obtain information about the current route in your Angular application.

Read more topics on angular here.