blazorsubmitsetfocusblazor-jsinteropblazor-editform

Blazor: Set focus on an element not work after submit


this code when submit button entered invoked. in "finally" i want to set focus to an InputText but it doesn't work.

private async Task SubmitBtn()
{
    if (_busy_submit_btn) return;
    _busy_submit_btn = true;
    try
    {
        var res = await myService.UpsertAsync(LetterId, myModel);
        if (res.Item1 != null)
        {
            myModel = res.Item1;
            await JsRuntime.ToastrSuccess(res.Item2);
            personsInMyModel = await myService.GetPersonWithLetterIdAsync(LetterId);
        }
        else
        {
            await JsRuntime.ToastrError(res.Item2);
        }

        myModel = new myDTO();
    }
    finally
    {
        _busy_submit_btn = false;
        await JsRuntime.InvokeVoidAsync("focusElementById", "NCode");
    }

}

Set focus on an element after submit


Solution

  • I am using an EditForm - when I change model instance, it drops and recreates the elements in the DOM - so it will need to set focus in OnAfterRenderAsync instead.