2

From Build a Navigation Menu with Bootstrap 4, I have created a top navigation menu:

<nav class="navbar navbar-fixed-top navbar-dark bg-inverse">
    <div class="container">
        <a class="navbar-brand">Angular Router</a>
        <ul class="nav navbar-nav" routerLinkActive="active">
            <li class="nav-item"><a class="nav-link" routerLink="home">Home</a></li>
            <li class="nav-item"><a class="nav-link" routerLink="about">About</a></li>
            <li class="nav-item"><a class="nav-link" routerLink="courses">Courses</a></li>
        </ul>
    </div>
</nav>

<router-outlet></router-outlet>

The problem is, when I click on a menu item like home, it is not shown as active. I haven't included bootstrap.js.

Instead of bootstrap.js & jQuery, what is the best way I can make selected menu as active in Angular 2?

1 Answer 1

6

Simply use RouterLinkActive directive on all routerLink items:

<li class="nav-item"><a class="nav-link" routerLink="home" routerLinkActive="active">Home</a></li>
<li class="nav-item"><a class="nav-link" routerLink="about" routerLinkActive="active">About</a></li>
<li class="nav-item"><a class="nav-link" routerLink="courses" routerLinkActive="active">Courses</a></li>

active is bootstrap's class which will highlight currently active link. You can read more about RouterLinkActive directive here.

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

5 Comments

Sorry. It is not working. When menu is clicked it gets gray background, but after clicking on any field like Text field, the menu is not highlighted anymore.
@jaks Well, something else is causing problem for you then, check out Angular's official example, that's how it is done: embed.plnkr.co/?show=preview (RouterLinkActive directive is used in app.component.ts)
Do I need to use ng-bootstrap? I have included only bootstrap css cdn.
@jaks Don't think that's the issue here. You can try to make your own css class which will change the background of your active tab and then assign that class to routerLinkActive to check if bootstrap is the problem here.
Thanks a million. I defined my own CSS class and it is working.

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.