Home > database >  Event for only when page location is changed in Blazor
Event for only when page location is changed in Blazor

Time:02-22

new to Blazor. I'm currently working on a Blazor application that uses DevExpress components, which make scrolling a little wonky. I want the application to load at the start of page whenever I navigate to a new page. Currently, a temporary fix I've found is to use the Main Navigation Layout's OnAfterRenderAsync method to call for this function.

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    await JsRuntime.InvokeVoidAsync("ScrollTop");
}

The above method is used in MainLayout component. It's implementation is available in the a different JS file which is

function ScrollTop() {

document.getElementsByClassName('content')[0].scrollTop = 0;

}

This is a somewhat clumsy method because although pages load at the top, any change in in-page components make it so the page scrolls up again. Is there a way to do this where the event would be fired only if the page location is changed?

CodePudding user response:

You can use this method. Create a new JavaScript file in your wwwroot folder. For example ScrollToTop.js. Inside it put your code with export function.

export function Scroll() {
document.getElementsByClassName('content')[0].scrollTop = 0;
}

In your component create an OnAfterRenderAsync method and inside it call your function:

    protected override async Task OnAfterRenderAsync(bool firstRender)
{
        await using var module = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./ScrollToTop.js");
        await module.InvokeVoidAsync("Scroll");
}

CodePudding user response:

Have this in your MainLayout.razor

@inject NavigationManager NavigationManager


protected override void OnInitialized() {
    NavigationManager.LocationChanged  = OnLocationChanged;
}

async void OnLocationChanged(object sender, LocationChangedEventArgs args) {        
    await JsRuntime.InvokeVoidAsync("ScrollTop");
}

public void Dispose() {
    NavigationManager.LocationChanged -= OnLocationChanged;
}
  • Related