angularroutesangular-routerlinkrouterlinkactive

Angular: clean way to bind template var based on active routerlink


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


Solution

  • 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>