On mobile, I open the responsive menu and click on a menu item <NavLink>
. I am routed to the new page, but the menu stays open and does not automatically collapse. When I click the <NavLink>
a second time, the menu collapses. How do I make it auto collapse after clicking on <NavLink>
the first time?
I'm using some of the code from the default Blazor template that looks like it would solve this problem, but it does not.
The navbar-collapse div
when menu is opened by button:
`
<div id="navbarNav" b-8i8utxilae="" style="">
The navbar-collapse div
when clicked once:
<div id="navbarNav" b-8i8utxilae="" style="">
The navbar-collapse div
when clicked twice:
<div id="navbarNav" b-8i8utxilae="" style="">
Here is all of the code.
<nav >
<div >
<div style="width: 50px;">
<a href="/">
<img src="/images/Magnolia_white.png" alt="no image" />
<span >Magnolia</span>
</a>
</div>
<button type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span ></span>
</button>
<div onclick="@ToggleNavMenu" id="navbarNav">
<ul >
<li >
<NavLink href="" Match="NavLinkMatch.All">
Home
</NavLink>
</li>
</ul>
</div>
</div>
</nav>
@code {
private bool collapseNavMenu = true;
private string? NavMenuCssClass => collapseNavMenu ? "collapse" : null;
private void ToggleNavMenu()
{
collapseNavMenu = !collapseNavMenu;
}
}
CodePudding user response:
At your toggle button you should replace data-bs-toggle="collapse" data-bs-target="#navbarNav"
with @onclick="ToggleNavMenu"
. Which means that instead of letting Bootstrap toggle the navigation menu with JavaScript, you should do it manually from the Blazor component, so that the collapseNavMenu
bool variable is always in sync with the state of the navigation menu.
<button type="button" @onclick="ToggleNavMenu">
<span ></span>
</button>
<div @onclick="ToggleNavMenu" >
<ul >
<li >
<NavLink href="" Match="NavLinkMatch.All">
Home
</NavLink>
</li>
</ul>
</div>