DrGriff
DrGriff

Reputation: 4906

Scroll MudTable to make selected item visible

I have a Blazor WASM application using a MudTable that displays many rows from List<T>.

The MudTable uses @ref="_mappingTable" to identify the table in code.

In code, I set the selected item:

_mappingTable.SetSelectedItem(specificItemFromTheList);
StateHasChanged();

This seems to work fine. However, I'd then like the table to automatically scroll so that item is now visible. It's not automatically doing that and not sure how to achieve that.

Upvotes: 0

Views: 1300

Answers (2)

Waleed Cordy
Waleed Cordy

Reputation: 1

function scrollToLastRow(tableId) {
    var table = document.getElementById(tableId);
    var rows = table ? table.getElementsByTagName("tr") : [];
    if (rows.length > 0) {
        var lastRow = rows[rows.length - 1];
        var lastRowTop = lastRow.offsetTop;
        var lastRowHeight = lastRow.offsetHeight;
        var tableContainer = document.querySelector("div.mud-table-container");
        if (tableContainer && lastRowTop + lastRowHeight > tableContainer.scrollTop + tableContainer.offsetHeight) {
            tableContainer.scrollTo({
                top: lastRowTop - tableContainer.offsetHeight + lastRowHeight,
                behavior: 'smooth'
            });
        }
    }
}

Upvotes: 0

RafBorrelli
RafBorrelli

Reputation: 266

There is an open issue requesting a new function "Scroll to row in MudTable" https://github.com/MudBlazor/MudBlazor/issues/5445

You can wait for that issue to be solved or try the alternative posted by the user geometrikal

Currently using this code to scroll a row into view. It assumes the table rows are all the same height.

export function scrollMudTableToRow(rowIndex) {
    var tableElement = document.querySelector("div.mud-table-container");
    var tableHeight = tableElement.offsetHeight;
    var tableOffset = tableElement.scrollTop;
    var tableRowHeight = tableElement.querySelector("tr.mud-table-row").scrollHeight;

    // Element is above view - scroll so it is at top
    if (rowIndex * tableRowHeight < tableOffset) {
        tableElement.scrollTo(0, rowIndex * tableRowHeight);
    }
    // Element is below view - scroll so that it is at bottom
    else if ((rowIndex + 1) * tableRowHeight > tableOffset + tableHeight) {
        tableElement.scrollTo(0, (rowIndex + 1) * tableRowHeight - tableHeight);
    }    
}

Upvotes: 1

Related Questions