I'm trying to change the class of a <span>
element based on a bool. I'm saving the value of the bool in the localstorage and the Console.WriteLine
shows me that SidenavClass
gets the correct value (class name). However, it does not update in the HTML. The classname
doesn't get added to the <span>
element.
I also tried using StateHasChanged()
, his doesn't seem to work.
It's a component in a component, in a component.
ProductCategoriesNavMenu.razor inside NavMenu.razor inside MainLayout.razor
Can someone help me figure out why it's not updating the classname in the HTML?
ProductCategoriesNavMenu.razor
@foreach (var productCategory in ProductCategoryDtos)
{
var link = "ProductsByCategory/" + productCategory.Id;
<div class="nav-item px-3">
<NavLink class="nav-link" href="@link">
<span class="@productCategory.IconCSS"></span><span class="@SidenavClass">@productCategory.Name</span>
</NavLink>
</div>
}
<div class="@SidenavClass">TEST</div>
@code {
public bool collapsedMenu { get; set; }
public string SidenavClass => collapsedMenu ? "collapsed-sidenav" : "";
public async Task CollapseMenuToggler()
{
await Task.Delay(500);
collapsedMenu = await LocalStorage.GetItemAsync<bool>("Menu Collapsed");
Console.WriteLine("collapsedMenu: " + collapsedMenu + ", Class: " + SidenavClass);
StateHasChanged();
}
}
NavMenu.razor
<ProductCategoriesNavMenu/>
@code {
public static string Class = "collapsed-sidenav";
[Parameter] public EventCallback<bool> CollapseSidebarEvent { get; set; }
public void CollapseMenu(MouseEventArgs e)
{
collapsedSidenav = !collapsedSidenav;
LocalStorage.SetItemAsync<bool>("Menu Collapsed", collapsedSidenav);
if(collapsedSidenav)
{
LocalStorage.SetItemAsync<string>("Collapse Class", Class);
}
else
{
LocalStorage.SetItemAsync<string>("Collapse Class", "");
}
CollapseMenuToggler();
CollapseSidebarEvent.InvokeAsync(collapsedSidenav);
}
}
MainLayout.razor
<NavMenu CollapseSidebarEvent="(e)=>SidenavCollapsedHandler(e)" />