I am designing a vertical navbar where the user clicks on the list item link and it will route to another component and at the same time change it to gray. I am currently re-using the gallery vertical nav component on each of the arts/nature/animals component.
However the behaviour is not expected when the user is routed to another component, I have to click the same list item link then it will be set to focus. I tried this on a normal html/css. It works perfectly but it does not work in Angular.
Could someone help me with this?
Here are my codes for my Gallery vertical nav bar:
gallery.component.html
<nav>
<ul>
<li tabIndex="1"><a routerLink="/arts">Arts</a></li>
</ul>
<ul>
<li tabIndex="1"><a routerLink="/nature">Nature</a></li>
</ul>
<ul>
<li tabIndex="1"><a routerLink="/animals">Animals</a></li>
</ul>
</nav>
gallery.component.css
ul {
list-style: none;
}
li {
padding: 10px;
border: 1px solid #d1d1d1;
}
/* handles when user is focusing on a menu */
li a:focus {
background-color: #8a8a8a !important;
color: white;
}
CodePudding user response:
This is happening because in regular HTML/CSS you're not re-rendering the DOM when you click on a link (I'm assuming) so it stays "active". Per the docs:
A link becomes active when you click on it.
Active is stateful in your HTML and only occurs when you click the link. If you refresh the page, for example, active state is toast. I believe you're looking for RouterLinkActive:
Tracks whether the linked route of an element is currently active, and allows you to specify one or more CSS classes to add to the element when the linked route is active.
Try changing gallery.component.html to:
<nav>
<ul>
<li tabIndex="1">
<a routerLink="/arts" routerLinkActive="active-link">Arts</a>
</li>
</ul>
<ul>
<li tabIndex="1">
<a routerLink="/nature" routerLinkActive="active-link">Nature</a>
</li>
</ul>
<ul>
<li tabIndex="1">
<a routerLink="/animals" routerLinkActive="active-link">Animals</a>
</li>
</ul>
</nav>
... and in gallery.component.css:
ul {
list-style: none;
}
li {
padding: 10px;
border: 1px solid #d1d1d1;
}
/* Applied when link is active */
.active-link {
background-color: #8a8a8a !important;
color: white;
}
Now, the RouterLinkActive
directive will watch for router changes and apply the active-link class to the active link. This is important because if the user, for example, navigates directly to /arts
you would want the active state applied, right? Same if they use their back button.