Home > OS >  Multi level Nav Menu Balzor server side application
Multi level Nav Menu Balzor server side application

Time:10-08

Working on a blazor server application and trying to make the multi level Navigation menu

Under Shared Component Navmenu.razor file, i added the code which is copied from bootstrap

enter image description here

Is really no easy-way to make a multi level Nav Menu in Blazor ?

CodePudding user response:

The answer to your problem is you should make a component out of it.

For example,

Start by creating a component with a boolean and a string.

Then create an element and give it the @onclick attribute. When the user clicks on the element, it fires the onclick event and it switches the boolean value to the opposite of what it was.

Finally, a string property tracks the boolean value and outputs the appropriate string that contains the style needed to show or hide a particular element.

CollapsableMenuItem.razor

<button @onclick="ToggleVisibility" class="btn btn-link" style="cursor:pointer;">Click me</button>
<br />
<span class="nav-item" style="@_style">
    I'm invisible until you click on the button
</span>

@code {
 private bool _collapsed;

 private string _style 
   => _collapsed ? "visibility:visible;" : "visibility:hidden;";

 public Task ToggleVisibility() {
   _collapsed = !_collapsed;
   return Task.CompletedTask;
 }
}

I created this .NET Fiddle to see it in action:

https://blazorfiddle.com/s/229e32g4

CodePudding user response:

As Dennis mentioned, you can build a component out of it. However, if you are fine with the basic functionality offered by bootstrap, just go with it. I have used it extensively without any issues. Also,

  1. There is no harm in using JavaScript with Blazor. A lot of libraries use it all the time. For some browser interactions (page refresh, getting viewport size etc) you have to use JavaScript.
  2. If you use bootstrap 5, there is no jQuery. It's pure JavaScript
  3. Most importantly, it's painful to get animation right in blazor. While you will get the core collapse/expand functionality very easily in blazor, the animation is tricky.

Finally, your styles are wonky because there is a conflict in styling between nav-link that comes bundled with the visual studio template and nav-link as described in bootstrap. Keep one of your choice. You will find the template css under the razor file of the menu component. Delete or mark !important depending on style that you want to keep.

  • Related