ksiegowybk
ksiegowybk

Reputation: 39

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.

Upvotes: 1

Views: 4898

Answers (3)

Anders Sundberg
Anders Sundberg

Reputation: 1

I did this in .Net 6 to set focus to an InputText, don't see why it shouldn't work for .Net5.

@page "/ListCustomers"
@inherits ListCustomersBase

<EditForm Model="@model" >

    <InputText id="inputText" @ref="inputText" @bind-Value="model" />
    
    <button id="setFocus" @onclick="@buttonSetFocus_click">Set focus</button>

</EditForm>

@code{
    string model = "";
    InputText inputText;

    void buttonSetFocus_click(EventArgs e)
    {
        if(inputText.Element.HasValue == true ) // don't 
        {
            inputText.Element.Value.FocusAsync();
        }
    }
}

Upvotes: 0

Brian Parker
Brian Parker

Reputation: 14613

The source code to the Input Components

For example this how I inherited InputText and extended it to get a reference to the underlying input element: builder.AddElementReferenceCapture(5, (__ref) => { Element = __ref; });

public class FInputText : InputText, IFocusInput
{
    public ElementReference Element { get; set; }
    protected override void BuildRenderTree(RenderTreeBuilder builder)
    {
        builder.OpenElement(0, "input");
        builder.AddMultipleAttributes(1, AdditionalAttributes);
        builder.AddAttribute(2, "class", CssClass);
        builder.AddAttribute(3, "value", BindConverter.FormatValue(CurrentValue));
        builder.AddAttribute(4, "onchange", EventCallback.Factory.CreateBinder<string?>(this, __value => CurrentValueAsString = __value, CurrentValueAsString));
        builder.AddElementReferenceCapture(5, (__ref) => { Element = __ref; });
        builder.CloseElement();
    }
}

Now that I have access to the element reference a simple extension to give me the same functionality as FocusAsync().

public static class FocusExtensions
{
    public static ValueTask FocusAsync(this IFocusInput focusInput)
        => focusInput.Element.FocusAsync();
}

I created a NuGet package with 5 of them done.

Here is the GitHub Repo for the source.

Upvotes: 2

Khant Htet Naing
Khant Htet Naing

Reputation: 168

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"/>

Upvotes: 0

Related Questions