In the post Highlight Currently Selected Menu Item Angular Routing Example we saw how you can highlight the selected menu option but there may be one problem with that, menu option configured with root path route always remain highlighted. In this post we’ll see how to fix the problem of root path route always remaining highlighted in Angular using routerLinkActiveOptions.
Link remaining highlighted problem
If you have configured your routes arrays something like as given below-
const routes: Routes = [ {path: '', component: HomeComponent}, {path: 'account', component: AccountComponent}, {path: 'service', component: ServiceComponent} ];
And the routeLink as given here-
<nav class="navbar navbar-expand-md bg-dark navbar-dark"> <div class="container-fluid"> <div class="collapse navbar-collapse" id="collapsibleNavbar"> <ul class="nav navbar-nav"> <li class="nav-item" routerLinkActive="active"> <a class="nav-link" routerLink="/">Home</a> </li> <li class="nav-item" routerLinkActive="active"> <a class="nav-link" routerLink="/account">Accounts</a> </li> <li class="nav-item" routerLinkActive="active"> <a class="nav-link" routerLink="/service">Services</a> </li> </ul> </div> </div> </nav> <div class="container"> <div class="row"><p></p></div> <div class="row"> <div class="col-md-12"> <router-outlet></router-outlet> </div> </div> </div>
Then you will see the problem of link associated with the root ("/") always remain highlighted.
You can see in the image even if Services menu link is clicked, ‘Home’ remains highlighted.
This problem occurs because Angular considers root path segment to be the part of all the paths. Even if path is either http://localhost:4200/service or http://localhost:4200/account, root path segment “/” is always there. That is the reason the Link associated with empty path (“/”) is always highlighted.
Using routerLinkActiveOptions
In order to solve this problem using routerLinkActiveOptions. With routerLinkActiveOptions you can pass a javascript object {exact:true} to direct Angular to make link active only when exact path matches.
<li class="nav-item" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}"> <a class="nav-link" routerLink="/">Home</a> </li>
With this configuration change ‘Home’ menu will only be highlighted when it is selected, as soon as you move away from this option it won’t remain highlighted anymore.
That's all for this topic Using RouterLinkActiveOptions to Fix Link Highlighted Problem. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Angular Tutorial Page
Related Topics
You may also like-
No comments:
Post a Comment