Tom Cat
Tom Cat

Reputation: 345

Show or Hide Side Menu in Blazor

I am a beginner with blazor.

Please tell me how to Show or Hide side menu of the Blazor standard template using a button.

Thank You Very Much !

Upvotes: 1

Views: 9504

Answers (1)

Daniel W.
Daniel W.

Reputation: 1198

Best is to go with your own server, create a new Class called ViewOptionService.cs. This will contain the logic and work as a singleton service. _navBarVisible will hold the status if the nav bar is hidden or not, while Toggle will change the state and NavBarClass will used to hide the div of the nav bar:

public class ViewOptionService
{
    private bool _navBarVisible = true;

    public Action OnChanged { get; set; }
    
    //Change state by click on the button
    public void Toggle()
    {
        _navBarVisible = !_navBarVisible;//Change
        if (OnChanged != null) OnChanged();//Callback for reload
    }

    //get additional css class for nav bar div
    public string NavBarClass
    {
        get
        {
            if (_navBarVisible) return String.Empty;//No additional css class for show nav bar
            return "d-none";//d-none class will hide the div
        }
    }
}

We must register ViewOptionService as a Service, so modify the Main in Program.cs:

public static async Task Main(string[] args)
{
    //..
    //Add next line to register
    builder.Services.AddSingleton<ViewOptionService>();

    await builder.Build().RunAsync();
}

Now we can inject this as service and use it in MainLayout.razor to add a css class to the div:

@inherits LayoutComponentBase
@inject ViewOptionService ViewOption

<div class="sidebar @ViewOption.NavBarClass">
    <NavMenu />
</div>

We can also inject it in the Index.razor (or somewhere else) to add a button:

@page "/"
@inject ViewOptionService ViewOption

<button @onclick="ViewOption.Toggle">Hide Menu</button>

One final step is missing, in case the value has changed we need to reload the MainLayout.razor, so we need to add a code part to the MainLayout:

@code {

    protected override async Task OnInitializedAsync()
    {
        ViewOption.OnChanged = () => { 
            StateHasChanged();//Refresh
        };
    }
}

=== Edit ===

I postet full code under https://github.com/DanielHWe/Hide-Blazor-NavBar-Sample

Upvotes: 5

Related Questions