Skip to content

InputText component should provide a FocusAsync() method #24446

@meziantou

Description

@meziantou

The PR #23316 introduced ElementReference.FocusAsync() which is convenient to focus an html element.
In my case I need to focus an <InputText> component in a form. There are 2 cases where I want to focus the element:

  • In OnAfterRenderAsync when firstRender is true (similar to autofocus)
  • On form submit to focus the element when the user doesn't provide a value

I currently use a custom component that inherits from InputText and provide a FocusAsync method.

@inherits InputText
@inject IJSRuntime JSRuntime

<input @ref="inputElement"
       @attributes="AdditionalAttributes"
       class="@CssClass"
       value="@CurrentValue"
       @oninput="EventCallback.Factory.CreateBinder<string>(this, __value => CurrentValueAsString = __value, CurrentValueAsString)" />

@code {
    private ElementReference inputElement;

    public ValueTask FocusAsync()
    {
        // could be replaced with inputElement.FocusAsync() with the next release
        return JSRuntime.InvokeVoidAsync("BlazorFocus", inputElement);
    }
}

In the parent component I can use FocusAsync when needed which works well.

I think InputBase<T> or each component should have a FocusAsync method, so I don't need to override components:

namespace Microsoft.AspNetCore.Components.Forms
{
    public class InputBase<T>
    {
+        public ValueTask FocusAsync();
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    affected-fewThis issue impacts only small number of customersarea-blazorIncludes: Blazor, Razor ComponentsenhancementThis issue represents an ask for new feature or an enhancement to an existing onehelp wantedUp for grabs. We would accept a PR to help resolve this issueseverity-majorThis label is used by an internal tool

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions