I have a standard - blazor - project which has the following components:
-> MainLayout.razor
-> NavMenu.razor
-> Pages/Index.razor
-> Pages/Sub1.razor
The MainLayout looks like this:
<div class="sidebar">
<NavMenu />
</div>
<div>@Body</div>
Now I want to exchange Data between my pages (index.razor, sub1.razor) and the navmenu so I could add something like this in navmenu:
<div><p>You are now on Page: @CurrentPageName</p></div>
How can I set (navMenu).CurrentPageName directly from within my page? I would expect that using a static class for that is not really a good option.
By using Blazor route parameters, you can pass values from one page to another page. Use NavigationManager to pass a value and route the parameter to another page. Follow this example to achieve passing values from one page to another. Get the passed Page1 parameter value in Page2.
You can get the current page title in Blazor by using the “title” property of the document object in JavaScript and by using a . JavaScript interop since there is no DOM accessibility in Blazor.
There are three main ways to communicate between components in Blazor. Chris Sainty has a good article outlining these: https://chrissainty.com/3-ways-to-communicate-between-components-in-blazor/
In this scenario a cascading value or a state container are probably the best options.
A cascading value would require a top-level component to contain the value, e.g. something that encapsulates both the <NavMenu>
and the @Body
:
@inherits LayoutComponentBase
<MenuState>
<div class="sidebar">
<NavMenu />
</div>
<div class="main">
<div class="top-row px-4">
<a href="http://blazor.net" target="_blank" class="ml-md-auto">About</a>
</div>
<div class="content px-4">
@Body
</div>
</div>
</MenuState>
Another approach is to use an injectable service that provides a State service, which you inject into both the <NavMenu>
and the page components.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With