Sometimes in your Angular app, you might need to identify which route the user is currently on.

And that's what I'll show you how to do in this guide.

Ready to go? Let's get started.

Lethal Injection

It all starts with an injection. That's an object that you define in your constructor.

In this case, you need to inject Router. Like most objects that get injected into Angular components, it's a service.

Specifically, it's a service that gives you info about navigation. So it's a helpful little animal if you're interested in getting the current route.

By the way: that current route gets expressed as a URL. It's just like the URL on any other website except 1) it's relative and 2) your Angular app is still a single-page app even though people navigate to different places with URLs.

So here's the starting point in your component:

constructor(private router: Router) { }

That's way we roll with Angular. Dependencies get injected via the constructor.

Of course, you'll need to add Router in addition to whatever other dependencies you've injected.

Getting Earl (or Getting URL)

Up to this point, all you've done is inject the Router service into your component. You still need to get the URL of the current route.

Here's some great news: that's really easy to do. Because the Router service offers a property appropriately named url.

So take a crack at something like this:

  ngOnInit(): void {
    console.log("The route is " + this.router.url);
  }

Once your application updates, go visit the route that points to that component. Then, check your developer tools console output in your browser. 

You should see output that looks like this:

The route is /dashboard

Of course your route will be different because you're probably not doing that in the dashboard component like I am.

You might have noticed that the route is relative. In other words, it doesn't have http://127.0.0.1:4200 (or whatever) in front of it.

Yep. That's the way the Router service reports back on routes.

I'd venture to guess that for 99% of the use cases, the relative URL is all you need. It's not likely you'll need to know the protocol, host, and port.

If you need everything, though, just go with something like this:

console.log(window.location.href);

Just like in good ol' JavaScript.

That will give you everything. But seriously think about why you need that much info. It's possible some refactoring is in order.

Wrapping It Up

Now you know how to get the current URL in an Angular app.

Feel free to put the code you've seen here in your own components. Then, you can add logic to follow based on the user's current route.

Have fun!

Photo by Mihis Alex from Pexels