Using Angular framework to build my website's front-end, I'm trying to include a button/icon capable of opening and closing this sidenav:
<nav id="left-sidenav" class="sidenav">
<div class="local_nav">
<a class="link" href="#">About</a>
<a class="link" href="#">Services</a>
<a class="link" href="#">Clients</a>
<a class="link" href="#">Contact</a>
</div>
</nav>
I found a cool hamburger fold-out menu on codepen.io, and I ended up modelling the HTML code this way.
<div id="menuToggle">
<input type="checkbox" onclick="toggleNav()" />
<span></span>
<span></span>
<span></span>
<ul id="menu"></ul>
</div>
With this being the toggleNav() function (added to index.html head):
<script>
//sidenav-width: 150px (this is defined in sidenav.component.scss)
function toggleNav() {
var x = document.getElementById("left-sidenav");
if (x.style.width === "0px") {
//openNav
x.style.width = "150px";
} else {
//closeNav
x.style.width = "0px";
}
}
</script>
So when the page is loaded, it looks like this [please don't mind the image, it's my first time using Angular and I'm trying to get better :) ]: Reloaded page
Now, for some reason, when trying to use this burger menu the first click doesn't trigger the onclick event, and the icon ends up transforming (as it should do) in a cross (see the codepen.io CSS). Page after the first click
On the second click though, the event seems to start working and the sidenav finally shows up, with the cross reverting into the burger icon. If I keep clicking on the burger, it just works as it should, with the icon being out of phase. Page after the second click; Page after the third click
This makes no sense to me, and I initially wanted to get the cross when the sidenav is shown, not when it's hidden. Does anyone know how to actually fix this?
You can change the implementation of the function toggleNav() for this:
In your .ts file add this.
toggle: boolean = false;
toggleNav() {
this.toggle = !this.toggle;
window.scrollTo(0, 0);
}
I've been struggling with this for 6 days now but I finally solved the problem just by changing the JS code this way:
<script>
//sidenav-width: 150px
var open = false;
function toggleNav() {
let x = document.getElementById("left-sidenav");
if (open == false) {
//openNav
x.style.width = "150px";
}
if (open == true) {
//closeNav
x.style.width = "0px";
}
open = !open;
}
</script>
It's not the most correct way to handle this in Angular, but it works. Let me know if you found this helpful or if there's a more proper way to solve this.