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 tabindex="0" @ref="myDiv">
To focus this div element when refreshing the page.
</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);
}
}
}
Share with