I want to style the css and add class when a link is active using routerLinkActive. I have tried in bootstrap and it works, but then when I got the custom CSS from the front end developer, it won't add the class that states that it is active, even when the route url is match the routeLink.
I am a bit frustated and have no idea what is wrong. I expect it will add class menu-active in the anchor when the route is active.
here's my code:
sidebar.component.html
<li class="menu-parent">
<a class="menu-item" routerLink="/dashboard" routerLinkActive="menu-active">
<i class="ti ti-anchor"></i>
<span class="menu-text">Dashboard</span>
</a>
</li>
I have tested like the code below, referenced from this question. I expect the i showed because the routerlink is active, but it doesn't, even when I am in the http://localhost:4200/dashboard.
<li class="menu-parent">
<a class="menu-item" routerLink="/dashboard" routerLinkActive #rla="routerLinkActive">
<i class="ti ti-anchor" *ngIf="rla.isActive"></i>
<span class="menu-text">Dashboard</span>
</a>
</li>
Hope someone could clear my frustration. Thank you.
Update:
The class is not even added when I inspect the element. Here's the screenshot of it:
I have found the solution. My routerLinkActive broke because I use *ngIf in my component selector. I supposed to make the navbar shown if the user had logged in, and the navbar was also a wrapper for my content. So I used *ngIf to hide the navbar if the user is not logged in. And that was where my problem start. My navbar contains sidebar and topbar, which I have merged to avoid adding *ngIf in the component selector again.
src/app/app.component.html
<app-navbar *ngIf="isLoggedIn; else loginpage"></app-navbar>
<ng-template #loginpage>
<router-outlet></router-outlet>
</ng-template>
the isLoggedIn in my code contains Boolean, whether the user has logged in or not.
The solution: every route will load the navbar, but I put the *ngIf="isLoggedIn" within the navbar divs, so if the user is not logged in, it won't show the sidebar and show the content only instead.
src/app/app.component.html
<app-navbar></app-navbar>
src/app/navbar/navbar.component.html
<div id="wrapper" [ngClass]="menu" *ngIf="isLoggedIn; else loginpage">
<div class="side-menu" id="sidebar-wrapper" >
// the sidebar HTML
</div>
<div class="wrapper-body">
<div class="top-menu" >
// the topbar HTML
</div>
<div class="content-wrapper">
<div class="row main-content">
<router-outlet></router-outlet>
</div>
</div>
</div>
</div>
<ng-template #loginpage>
<router-outlet></router-outlet>
</ng-template>
I never thought that putting *ngIf in the component selector will waste 2-3 days of my app development. I never find in the documentation that structural directives cannot be added in component selector. Any of you find that in the documentation? Thank you for all your help guys!