blazorblazor-server-side

How do I set focus to a text box in Blazor


How do I set focus to a textbox in Blazor? So far the only way we have found is with JavaScript.


Solution

  • 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);
            }
       }
     }
    

    JavaScript

    <script>
    
        window.exampleJsFunctions =
        {
            focusElement: function (element) {
               element.focus();
            }
        };
    </script>
    

    Hope this helps...