This code will help you to understand how to set the focus to an element in Blazor.
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); } } }
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
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.
need an explanation for this answer? contact us directly to get an explanation for this answer