Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

blazor - How to set the focus to an InputText element?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 still 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...