0

How can I check if the current route matches my routerLink string?

class TestComponent implements OnInit {
    @Input()
    public routerCmd: string;

    constructor(private router: Router) {}

    ngOnInit(): void {
        // Pseudo code
        if (this.router.urlFromCmd(this.routerCmd) === this.router.url) {
            alert('Match!');
        }
    }
}
<a [routerLink]="routerCmd">Link</a>

Usage

<test-component routerCmd="./tests"></test-component>

What I do not search:

<a [routerLink]="routerCmd" routerLinkActive="active">Link</a>

btx
  • 1,972
  • 3
  • 24
  • 36
  • In de Object Router you have a method "isActive()": see the [docs](https://angular.io/api/router/Router#isActive) – Eliseo Dec 05 '22 at 14:25

1 Answers1

0

Looks like the correct URL is not available at ngOnInit. You can take advantage of RxJs for continuous checking with streams.

import { filter, map, mapTo } from 'rxjs';
import { NavigationEnd, Router } from '@angular/router';

// ... inside component
constructor(private router: Router) {}
// ...
const currentUrl$ = this.router.events.pipe(
  // We want the final updated URL, so we skip/filter out the rest:
  filter(event => event instanceof NavigationEnd),
  // We don't want anything from the event, but now we know the URL is correct:
  mapTo(this.router.url), // mapTo is same as: map(() => this.router.url),
);
const isCurrentLinkActive$ = currentUrl$.pipe(
  map(url => this.routerCmd === url), // boolean
);

isCurrentLinkActive$.subscribe(isActive => {
  if (isActive) {
    alert('Active');
  }
})

If your routerCmd variable is not a valid URL path, you can build the path with router.createUrlTree([]) but I don't think that's the question.

Ajit Panigrahi
  • 752
  • 10
  • 27
  • If there is no option to check a Router command for activeness in the TS code, creating the URL tree is in deed a way to achieve this. However I'm not able to get a full URL from my Router command that I can compare against `window.location.href`. Regarding your solution: Im not doing a routing event. I just was expecting to find any functions in the Router class that I can use – btx Dec 05 '22 at 14:18
  • try `router.parseUrl` – hawks Dec 05 '22 at 14:24
  • @hawks unfortunately parseUrl it does not resolve dot notation to a full path – btx Dec 05 '22 at 15:31