0

Building an Angular 4 app, but I would accept an answer that works with v5+ as well. I have a navbar composed of navigation buttons like this:

<custom-button routerLink="/some-route"></custom-button>

I know I can add a custom class "active" to the element based on whether the current route matches the button's routerLink with:

<custom-button routerLink="/some-route" routerLinkActive="active"></custom-button>

However I need a way to bind an input value based on this condition (whether the route is current), like:

<custom-button routerLink="/some-route" [inputFlag]="isOnCurrentRoute">
</custom-button>

So the idea is that inputFlag would be set to true if the button's routerLink refers to the current route. I know this could be accomplished by injecting ActivatedRoute and building a function that takes the value of the button's routerLink and returns true if it matches the current route.

<custom-button routerLink="/some-route" 
  [inputFlag]="isOnCurrentRoute('/some-route')">
</custom-button>

That's a lot of overhead though; wondering if Angular exposes an API to do all that within the template

BeetleJuice
  • 39,516
  • 19
  • 105
  • 165

2 Answers2

1

You can define the function isOnCurrentRoute like this

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

constructor(private router: Router) {}

isOnCurrentRoute(path): Observable<boolean> {
  return this.router.events.pipe(
    filter(event => event instanceof NavigationEnd),
    map(event => event.url === path)
  );
}

and use it on your template with an async pipe

<custom-button routerLink="/some-route" 
  [inputFlag]="isOnCurrentRoute('/some-route') | async">
</custom-button>

Hope this helps

joyBlanks
  • 6,419
  • 1
  • 22
  • 47
  • Hey thanks for your response. I am able to design such a function just fine. In fact I hint at a(nother) way to do this in the OP. My question is whether Angular offers a seamless way to do it entirely in the template – BeetleJuice Sep 06 '19 at 00:15
1

So I kept thinking about it and if Angular does have a feature of doing what you were looking for routerLinkActive attribute in conjunction to routerLink we can use it to hack a little bit just in the template itself and no JS/TS code, by checking the class name which gets assigned by routerLinkActive.

Solution:

<custom-button #customBtn
  routerLink="/some-route" 
  routerLinkActive="active"
  [inputFlag]="customBtn.classList.contains('active')"
></custom-button>
joyBlanks
  • 6,419
  • 1
  • 22
  • 47