Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exchange Data between Page and NavMenu in Blazor

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.

like image 939
Ole Albers Avatar asked Mar 29 '20 10:03

Ole Albers


People also ask

How to pass values from one page to another in Blazor?

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.

How can I get current page name in Blazor?

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.


Video Answer


1 Answers

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.

like image 72
Quango Avatar answered Oct 20 '22 16:10

Quango