Q:

How to set the focus to an element in Blazor?

0

This code will help you to understand how to set the focus to an element in Blazor.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

To set the focus to a HTML element in Blazor, use the JavaScript interop to pass the HTML element and then use focus JavaScript method.

[script.js]

window.SetFocusToElement = (element) => {
         element.focus();
};
[index.razor]

@inject IJSRuntime jsRuntime

<div class="jumbotron" tabindex="0"  @ref="myDiv">
</div>

@code {
    string KeyPressed = "";
    protected ElementReference myDiv;  // set the @ref for attribute

    protected async override Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await jsRuntime.InvokeVoidAsync("SetFocusToElement", myDiv);
        }
    }
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now