How to Get the Current Route in Angular 15

Spread the love

Hello Guys,

In this tutorial, we’ll demonstrate how to get the current route in Angular 15. We provide a simple example of how to access the current route path in Angular 15.

To obtain the current route in Angular 15, you can utilize the Angular Router library within your component file. This library allows you to easily access the current route path.

In certain instances while working with an Angular application, you might find the need to access the current path or the current router URL. We’ll guide you through how to fetch the current URL in Angular promptly.

Here’s the essential solution:

You can obtain the current route name as shown below. Additionally, we’ve included a comprehensive example and output to help you understand:

Example of How to Get the Current Route in Angular 15:
this.router.url;
  
window.location.href;

Now, I’ll provide a comprehensive example for you. Feel free to incorporate the code into your component file following the format displayed below.

Also Read: how to integrate chatgpt API in laravel 10

Component File
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
   
@Component({
  selector: 'app-posts',
  templateUrl: './posts.component.html',
  styleUrls: ['./posts.component.css']
})
export class PostsComponent implements OnInit {
  
  constructor(private router: Router) { }
  
  ngOnInit() {
    console.log(this.router.url);
    console.log( window.location.href);
  }
  
}

I hope it can be useful to you.

Leave a Comment