Moffen
Moffen

Reputation: 2003

How to scroll a MudBlazor DataGrid to bottom when page loads?

I have a MudBlazor DataGrid and need to scroll it from the bottom not from the top. This means that on page load it needs to have the scrollbar at the bottom.

I have tried some javascript interop but beacuse the muddatagrid outer div itself isn't the one scrolling I don't know what element to use JS interop on.

https://mudblazor.com/api/datagrid#pages

<MudDataGrid id="workoutPickerGrid" Dense=true T="Workout" Items="@data.Workouts.MyWorkouts" Breakpoint="Breakpoint.None" Filterable="true" Virtualize="true" HeaderClass="d-none" Height="100%" Style="height:100%;" ShowColumnOptions="false">
    <ChildRowContent>
        <div class="d-flex justify-space-between align-center" @onclick=@(()=>navManager.NavigateTo($"/Workouts/View/{context.Item.ID}"))>
            <MudText Typo="Typo.subtitle2">@context.Item.Name</MudText>
            <MudText Typo="Typo.body2">@context.Item.StartedAt.GetTimeSinceString()</MudText>
        </div>
        <MudText Typo="Typo.body2">@context.Item.StartedAt.ToLongDateString()</MudText>
    </ChildRowContent>
</MudDataGrid>

<script>
    window.onload = function () {
        var objDiv = document.getElementById("workoutPickerGrid");
        objDiv.scrollTop = objDiv.scrollHeight;
    }
</script>

Upvotes: 2

Views: 1037

Answers (1)

Anu6is
Anu6is

Reputation: 2657

You can use the IScrollManager which provides a ScrollToBottomAsync method. You'd need to identify a selector for the element that you wish to scroll. In the case of a data-grid, you can use the table container.

Once you've injected the IScrollManager, you can do something like

protected override async Task OnAfterRenderAsync(bool firstRender) 
{
    await ScrollManager.ScrollToBottomAsync(".mud-table-container", ScrollBehavior.Smooth);
}

Upvotes: 4

Related Questions