Setfocus for some Radzen Controls

I am using Radzen controls without the IDE in Blazor server-side. I found the following code works for some controls.I wonder if there's a work-around for others.

RadzenTextBox accepts and passes on, for example, an id="txtName" parameter to the final code. The same is not true for RadzenDatePicker. I haven't checked all the controls, but it does work for RadzenTextBox.

given

<RadzenTextBox Name="txtName" @bind-Value="@company.Name" id="txtName" />

Here's the javascript that goes into your _Host.cshtml

// Focus a control by its ID
function FocusControlByID(ControlID) {
    var ctrl = document.getElementById(ControlID);
    if (ctrl !== null) { ctrl.focus(); }
}

back to your component.

You'll need to inject javascript:
@inject IJSRuntime JSRuntime

Then call it as follows in OnAfterRenderAsync

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if(firstRender )
        {
            await JSRuntime.InvokeVoidAsync("FocusControlByID", "txtName");
        }
    }

There are more routines and more advanced ways to implement the above in this tip, credit to Scott Ward from this link. [Blazor: Using JavaScript in a More Structured Way by Using Extension Methods - CodeProject]

There is already such function in Radzen.Blazor.js:

1 Like