How do I set focus to a textbox in Blazor? So far the only way we have found is with JavaScript.
There is no other way to do it... You can use JSInterop to do this, as follows:
<input type="text" @ref="myref"/>
@code {
private ElementReference myref;
[Inject] IJSRuntime JSRuntime { get; set; }
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await
JSRuntime.InvokeVoidAsync("exampleJsFunctions.focusElement", myref);
}
}
}
<script>
window.exampleJsFunctions =
{
focusElement: function (element) {
element.focus();
}
};
</script>
Hope this helps...