2

I try to add an underline on the active-item in my NavBar component by binding the return value of the isActive() function. isActive() compares the url path with the string value passed in and returns true or false.

When I click on either item in the NavBar component, the isActive() function runs and the underline displays as expected on the NavBar element that corresponds to the page I navigated to.

However when I click an anchor tag outside of the NavBar component, the isActive() function doesn't get run again, so the underline remains on the navbar element for the previous page:

Class binding refresh issue

NavBar HTML:

<div class="anchor-wrapper" [class.active-item]="isActive('/dashboard')"> 
    <a [routerLink]="['/dashboard']">Dashboard</a>
</div>
<div class="anchor-wrapper" [class.active-item]="isActive('/inventory')">
    <a [routerLink]="['/inventory']">Inventory</a>
</div>

NavBar TS:

isActive(path) {
    return (url.parse(window.location.href).pathname === path) ? true : false;
}

Dashboard HTML:

<a (click)="onVehicleStatusClick()" RouterLinkActive="active"> {{promotedCount}} </a>

Dashboard TS:

onVehicleStatusClick(){
    this.router.navigate(['/inventory']);
}

How do I ensure that isActive() runs again when I navigate to another route outside of the NavBar component?

Many thanks from an Angular newbie

5
  • 3
    what about using built in routerLinkActive ? Have you tried it? Commented Jul 18, 2018 at 14:23
  • I saw routerLinkActive in the legacy code, but after checking the Angular documentation just now, I don't think it was being used properly. Lemme try and I'll let you know! Commented Jul 18, 2018 at 14:29
  • It is stable: angular.io/api/router/RouterLinkActive Commented Jul 18, 2018 at 14:30
  • It worked! If you want to post it as an answer, i'll accept it. thanks a ton Commented Jul 18, 2018 at 14:30
  • Sure. no problem. I will Commented Jul 18, 2018 at 14:32

1 Answer 1

1

You can use routerLinkActive directive as follows:

NavBar HTML:

<div class="anchor-wrapper" routerLinkActive="isActive('/dashboard')"> 
    <a [routerLink]="['/dashboard']">Dashboard</a>
</div>
<div class="anchor-wrapper" routerLinkActive="isActive('/inventory')">
    <a [routerLink]="['/inventory']">Inventory</a>
</div

Docs

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.