Eric R
Eric R

Reputation: 713

Angular 2 - Match URL to Route

Is it possible to take a URL or path and find out which route it matches in the code-behind?

Ex: Router.matchRoute('my/route') returns information about the matching route, like:

{
  path: 'my/route',
  component: HeroListComponent,
  data: { title: 'Heroes List' }
}

Basically, what I'm trying to do is to tell if the route of my current URL/path matches that of the one being navigated to.

Upvotes: 3

Views: 11004

Answers (1)

Stephen R. Smith
Stephen R. Smith

Reputation: 3400

If you want to get the current URL and make some decisions in the component code based on what it is, for example adding a style to colour the current item in a navigation menu, then you can get the current URL from the Router and compare it to a known value to do something.

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

 constructor(
    private router: Router
 ) {}

Then you can write functions to check for a particular route:

 isSomePage() {
    if (this.router.url.includes('/my-page-path/')) {
        return 'active';
    } else {
        return '';
    }
 }

And then bind thing function to ngClass to add the class (active) to that item and style it with css.

 <div [ngClass]="isSomePage()">
    "colour me when the URL matches the isSomePage function"
 </div>

Then style this via css

div.active {
    color: white;
    background-color: red;
}

In the case where you're staying in one place and want to monitor the URL for changes, you can subscribe to router.events, for example if you were passing an 'id' variable via URL like this:

http://localhost:4000/#/home/my-component/?id=1146605

You could subscribe to the changes in id values - in this example I'm logging the values to the console, but you can do whatever you like with the value once you've got it here.

import { Router, NavigationEnd, Params } from '@angular/router';

var routerPassedParam

  ngOnInit() {
    this.router.events
      .filter(event => event instanceof NavigationEnd)
      .subscribe(event => {
        console.log("event", event);
        this.route
          .queryParams
          .subscribe(params => {
            // Defaults to 0 if no query param provided.
            var routerPassedParam = +params['id'] || 0;
            console.log('Query param routerPassedParam: ', routerPassedParam);
          });
      })
}

Upvotes: 2

Related Questions