Set focus on InputText in Blazor without JS

Could You tell me is there possible to set a focus on InputText in Blazor without JS using .Net 5? Maybe I'm wrong, but fallowing the cases in the documentation i need a ref to an input (not InputText) before i set focus. But maybe there is a way to do that? Best regards.

2 answers

  • answered 2020-11-25 07:24 enet

    You can derives from InputText, and use ElementReference.FocusAsync()

    InputTextSetFocus.razor

    @inherits InputText
      
    <input @ref="inputElement"
           @attributes="AdditionalAttributes"
           class="@CssClass"
           value="@CurrentValue"
           @oninput="EventCallback.Factory.CreateBinder<string>(this, __value => CurrentValueAsString = __value, CurrentValueAsString)" />
    
    @code {
        private ElementReference inputElement;
    
        protected override void OnAfterRender(bool firstRender)
        {
             base.OnInitialized();
             inputElement.FocusAsync();
           
        }
    
       
    }
    

    Usage

    @page "/"
    
    <EditForm Model="employee">
        <InputTextSetFocus @bind-Value="@employee.ID" />
    </EditForm>
    
    @code
    {
        private Employee employee = new Employee();
    
        public class Employee
        {
            public string ID { get; set; }
            public string Name { get; set; }
        }
    }
    

  • answered 2020-11-25 08:52 Khant Htet Naing

    In .Net 5 , you can use a FocusAsync method on ElementReference for the UI focus on that element.

    <button @onclick="() => textInput.FocusAsync()">Set focus</button>
    <input @ref="textInput"/>