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
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):
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
@code {
private ElementReference username;
public async Task SetFocusAsync()
{
await username.FocusAsync(JSRuntime);
}
}