Razor component
value is not updating inside LocationChanged
event handler.
I have created a Razor component Breadcrumb.razor
. I'm using this component inside my MainLayout.razor
page.
I need to update my breadcrumb values on Navigation.LocationChanged
event which is invoking fine when I navigate. But the problem is my values are not updating.
@inject NavigationManager Navigation
<nav aria-label="breadcrumb">
<ol class="breadcrumb bg-transparent mb-0 pb-0 pt-1 px-0 me-sm-6 me-5">
@if (string.IsNullOrEmpty(Module) && string.IsNullOrEmpty(Function))
{
<li class="breadcrumb-item text-sm text-dark active"><i class="fa fa-home text-primary"></i> Dashboard</li>
}else if (!string.IsNullOrEmpty(Module) && string.IsNullOrEmpty(Function))
{
<li class="breadcrumb-item text-sm"><a class="opacity-5 text-dark" href="/"><i class="fa fa-home text-primary"></i> Dashboard</a></li>
<li class="breadcrumb-item text-sm text-dark active" aria-content="page">@Module.Humanize()</li>
}
else if (!string.IsNullOrEmpty(Module) && !string.IsNullOrEmpty(Function))
{
<li class="breadcrumb-item text-sm"><a class="opacity-5 text-dark" href="/"> <i class="fa fa-home text-primary"></i> Dashboard</a></li>
<li class="breadcrumb-item text-sm"><a class="opacity-5 text-dark" href="/@Module">@Module.Humanize()</a></li>
<li class="breadcrumb-item text-sm text-dark active" aria-current="page">@Function.Humanize()</li>
}
</ol>
</nav>
@code {
protected string? Module{ get; set; }
protected string? Function{ get; set; }
protected override void OnInitialized()
{
Navigation.LocationChanged += (object? sender,LocationChangedEventArgs e) =>
{
ChangeLink();
};
}
protected void ChangeLink()
{
var Parameters = Navigation.ToBaseRelativePath(Navigation.Uri).Split('/');
if (Parameters.Length > 1)
{
Module = Parameters[0];
Function = Parameters[1];
}
else if (Parameters.Length > 0)
{
Module = Parameters[0];
Function = string.Empty;
}
else
{
Module = string.Empty;
Function = string.Empty;
}
}
}
You need to add a StateHasChanged()
at the end of your handler method as the event you're subscribing to is a .NET EventHandler
delegate, specifically EventHandler<LocationChangedEventArgs>
event.
These events do not automatically call StateHasChanged()
thereby, notifying the UI that the component has changed and needs to rerender. Unlike the Blazor EventCallback
events, which do.