Search code examples
c#blazorblazor-client-sideblazor-webassembly

Issue giving up focus on control


I am running into an odd issue using Blazor Webassembly. I have a component that has 2 text boxes. For some reason, if I type anything into the first text box, then try to either tab to the second text box or click in the second text box, I have to do it twice. It's like the first tab or click doesn't register. After playing around with it, I was able to minimally duplicate the issue. The issue seems to happen when I have both a model binding on the control and I use a @ref attribute.

Here is my .cshtml file:

@inject IJSRuntime JsRuntime
@page "/"


<div>
    <input class="form-control" id="first-text-box" type="text" @ref="TextBoxControl" @bind="_model.Box1" />
</div>
<div>
    <input class="form-control" id="second-text-box" type="text" @bind="_model.Box2" />
</div>


@code {
    private ElementReference TextBoxControl { get; set; }
    private readonly BoxClass _model = new BoxClass();

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await JsRuntime.InvokeVoidAsync("jsFunctions.focusElement", TextBoxControl);

        await base.OnAfterRenderAsync(firstRender);
    }
}

Here is the focusElement javascript function:

window.jsFunctions = {
    focusElement: function(element) {
        element.focus();
    }
};

Finally, here is a Fiddle of the issue to see it happen live: https://blazorfiddle.com/s/kph6msiv

Like I said, just type something into the first text box, then try to tab or click to the next text box and you'll see that you'll need to do it twice.


Solution

  • You are focusing every time it renders, which happens when Blazor data binds, which happens when you exit the control.

    Instead, only call your JavsScript if firstRender is true