How to set the focus to an InputText element?

半世苍凉 提交于 2020-12-25 10:34:53

问题


Using the example from the Microsoft docs, I'm trying to programmatically set the focus to an input element.

Unfortunately, the example uses a standard <input type="text"> whereas I want to use it for an InputText element.

The Microsoft example uses an extensions method that takes an ElementReference:

public static Task Focus(this ElementReference elementRef, IJSRuntime jsRuntime)
{
    return jsRuntime.InvokeAsync<object>(
        "exampleJsFunctions.focusElement", elementRef);
}

Using an InputText, I see no way of obtaining such an ElementReference.

Providing my own Focus() overload with an InputText instead, compiled but showed no visual result. Therefore I'm clueless.

My question

How can I programmatically set the focus to an InputText element?


回答1:


You can add id parameter to your InputText and modify your Focus method and JavaScript code.

public async Task Focus(string elementId)
{
    await JSRuntime.InvokeVoidAsync("exampleJsFunctions.focusElement", elementId);
}
focusElement: function (id) {
    const element = document.getElementById(id); 
    element.focus();
}

Note: this is more a workaround than a proper solution, but Blazor doesn't seem to support it directly.




回答2:


In .NET5 it will be much simpler:

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

NOTE: this feature was introduced in .NET5 Preview 8 so might change until the final release!

Also worth mentioning that in .NET5 RC1 JavaScript isolation was introduced via JS Module export/import. So if you steel need to use JS interop do not pollute window object.

Update: .NET 5 was released and this feature works unchanged.

Also found a cool Nuget package which can do some convenient JS tricks for you e.g.: focusing previously active element without having a @ref to it. See docs here.




回答3:


I was able to accomplish this by entering the JavaScript directly in the Host.chtml file (you can also add a .js file like the walkthrough suggests):

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

Next, in an extension file, I've added the extension (NOTE: I renamed Focus to FocusAsync because of naming standards:

public static async Task FocusAsync(this ElementReference elementRef, IJSRuntime jsRuntime)
{
    await jsRuntime.InvokeVoidAsync(
        "exampleJsFunctions.focusElement", elementRef);
}

Then in the razor page (or component), inject the IJSRuntime, Add an ElementReference and tie it to the element you want to focus (Note: Method names were changed to abide to naming standards):

@inject IJSRuntime JSRuntime
@using JsInteropClasses

<input @ref="username" />
<button @onclick="SetFocusAsync">Set focus on username</button>

@code {
    private ElementReference username;

    public async Task SetFocusAsync()
    {
        await username.FocusAsync(JSRuntime);
    }
}



回答4:


There are a couple of ways to set focus on an element the Blazor native way. Here's one:

Create a class that derives from the InputBase<string> which is the base class of InputText with the same functionality of InputText. In short, copy the code of InputText to your newly created class, and add the necessary functionality. Here's the new class: TextBox.cs

public class TextBox : InputBase<string>
    {

        private ElementReference InputRef;
        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, (value) => {
                InputRef = value; } );


            builder.CloseElement();


    }
        [Inject] IJSRuntime JSRuntime { get; set; }

        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
            {
                await JSRuntime.InvokeVoidAsync("exampleJsFunctions.focusElement", InputRef);
            }
        }

        protected override bool TryParseValueFromString(string value, out string result, out string validationErrorMessage)
        {
        result = value;
        validationErrorMessage = null;
        return true;
        }
        }

   } 

Place this script at the bottom of the _Host.cshtml file, just below

<script src="_framework/blazor.server.js"></script>

<script>

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

Things to note: 1. Define an ElementReference variable to hold reference to the input element. 2. In the BuildRenderTree method I've added code to capture a reference to the input element 3. Call the focusElement JavaScript function from the OnAfterRenderAsync method. This is performed only once. Note that I cannot use the OnInitializedAsync method which is executed only once, but the ElementReference variable may contain null. 4. Note that you cannot run any of the forms components without EditForm...

IMPORTANT: Pressing Ctrl+F5, when your browser is in a minimized state may interfere with seeing the cursor in the text element.

Code for usage:

<EditForm  Model="@employee" OnValidSubmit="@HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <TextBox @bind-Value="@employee.Name"/>

    <button type="submit">Submit</button>
</EditForm>

@code {
    private Employee employee = new Employee();

    private void HandleValidSubmit()
    {
        Console.WriteLine("OnValidSubmit");
    }

    public class Employee
    {
        public int ID { get; set; } = 1;
        public string Name { get; set; } = "Nancy";
    }
} 



回答5:


Possibly redundant now .net 5 is out, but if you don't want to hard code an element's Id or derive your own input class, an easy way to achieve this is to just add a CSS class to the element, and then find and set focus to that using getElementsByClassName.

Create a script to contain the helper:

var JSHelpers = JSHelpers || {};

JSHelpers.setFocusByCSSClass = function () {
    var elems = document.getElementsByClassName("autofocus");
    if (elems.length == 0)
        return;
    elems[0].focus();
};

Create a shared 'AutofocusByCSS' component to handle calling the JS at the right time:

@inject IJSRuntime JSRuntime
@code {
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender) JSRuntime.InvokeVoidAsync("JSHelpers.setFocusByCSSClass");
    }
}   

Then in your page:

<InputText @bind-Value="editmodel.someThing" class="form-control autofocus" />

<AutofocusByCSS />

Works on anything that boils down to a standard HTML element and makes it easier to change the autofocus target by changing the class name output.



来源:https://stackoverflow.com/questions/59137973/how-to-set-the-focus-to-an-inputtext-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!