Services

MudBlazor provides several useful services.

BrowserViewportService

Provides functionality to get the current view port size, to monitor the browser viewport size for any changes and to get the current breakpoint.

ResizeObserver

The ResizeObserver is similar to BrowserViewportService but for elements instead of the browser window.

Don't inject the IResizeObserver directly. Always use the IResizeObserverFactory instead.

This div is 0 px wide

@using MudBlazor.Interop
@using MudBlazor.Services
@inject IResizeObserverFactory ResizeObserverFactory
@implements IAsyncDisposable

<div @ref="_divReference" style="width: 100%; text-align: center;">
    <MudText>This div is @_divWidth px wide</MudText>
</div>
@code {
    private IResizeObserver _resizeObserver;
    private ElementReference _divReference;
    private double _divWidth;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);

        if (firstRender)
        {
            _resizeObserver = ResizeObserverFactory.Create();
            _resizeObserver.OnResized += ResizeObserverOnResized;
            await _resizeObserver.Observe(_divReference);
            _divWidth = _resizeObserver.GetWidth(_divReference);
            StateHasChanged();
        }
    }

    public async ValueTask DisposeAsync()
    {
        if (_resizeObserver != null) await _resizeObserver.DisposeAsync();
    }

    private void ResizeObserverOnResized(IDictionary<ElementReference, BoundingClientRect> changes)
    {
        _divWidth = changes.Values.LastOrDefault()?.Width ?? 0;
        StateHasChanged();
    }
}
ScrollManager

This service provides general scroll functionality for scrolling.

@inject IScrollManager ScrollManager

<MudStack Row="true">
    <MudButton OnClick="@ToggleScrollLockAsync" Variant="Variant.Filled" EndIcon="@LockScrollBtIcon">@LockScrollBtText</MudButton>
    <MudButton OnClick="@(() => ScrollManager.ScrollIntoViewAsync("#iresizeobserver", ScrollBehavior.Smooth))" Variant="Variant.Filled">Scroll to resize observer</MudButton>
</MudStack>
@code {
    private bool _scrollIsLocked;
    private string LockScrollBtText => _scrollIsLocked ? "Unlock scroll" : "Lock scroll";
    private string LockScrollBtIcon => _scrollIsLocked ? Icons.Material.Outlined.LockOpen : Icons.Material.Outlined.Lock;

    private async Task ToggleScrollLockAsync()
    {
        if (_scrollIsLocked) await ScrollManager.UnlockScrollAsync();
        else await ScrollManager.LockScrollAsync();

        _scrollIsLocked = !_scrollIsLocked;
    }
}
ScrollListener

Provides functionality to listen for scroll events for a specific element.

Don't inject the IScrollListener directly. Always use the IScrollListenerFactory instead.

An unhandled exception has occurred. See browser dev tools for details. Reload 🗙