btx
btx

Reputation: 2497

Check if router link is active in Angular using Typescript

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>

Upvotes: 0

Views: 954

Answers (1)

Ajit Panigrahi
Ajit Panigrahi

Reputation: 792

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.

Upvotes: 0

Related Questions