How to set focus to a specific control, that is not the first, after dialog is opened ?

I understand that the SfDialog, by behavior, set focus on first component of the EditForm and this is a nice feature, but in this case I need to set the focus to another control that is not the first.  I tried using the dialog's OnOpen event but it didn't work.  Please see attached project . 


<SfButton @onclick="@(() => isVisible = true )">Open Dialog</SfButton>

<SfDialog Visible="@isVisible" Width="400" Height="500" ShowCloseIcon="true" IsModal="true" AllowDragging="true" EnableResize="true">

    <DialogEvents OnOpen="SetFocus" Opened="SetFocus" Closed="OnClosed_MainDlg" />

    <DialogTemplates>

        <Content>

            <EditForm Model="@model">

                <DataAnnotationsValidator />

                <SfNumericTextBox @bind-Value="@model.MileageIn" TValue="int?" CssClass="mb-3" />

                <SfTextBox @ref="txtBox" @bind-Value="@model.LocIn" CssClass="mb-3" />

            </EditForm>

            <SfButton @onclick="@(() => SetFocus() )">Set Focus</SfButton>

        </Content>

    </DialogTemplates>

</SfDialog>


@code {

    bool isVisible = false;

    Model model = new();

    SfTextBox txtBox;


    async Task SetFocus()

    {

        await txtBox.FocusAsync();

    }


    class Model

    {

        public int? MileageIn { get; set; }

        public string LocIn { get; set; }

        public string FuelIn { get; set; }

    }


    void OnClosed_MainDlg()

    {

        isVisible = false;

    }

}



Attachment: RPTest_d63fe5f0.zip

1 Reply 1 reply marked as answer

VY Vinothkumar Yuvaraj Syncfusion Team January 30, 2023 04:21 PM UTC

Hi Ben,


You can use the Dialog Opened event to achieve your requirement. Please refer to the code below and the attached sample for your reference.


index.razor

<SfDialog

    <DialogEvents OnOpen="SetFocus" Opened="@onOpen" Closed="OnClosed_MainDlg" />

</SfDialog>

@code{

  private async Task onOpen(Syncfusion.Blazor.Popups.OpenEventArgs args)

    {

        args.PreventFocus = true;

       await txtBox.FocusAsync();

    }

}


Documentation:https://blazor.syncfusion.com/documentation/dialog/how-to/prevent-the-focus-on-the-first-element


API : 

 https://blazor.syncfusion.com/documentation/dialog/events#opened


Attachment: RPTest_24f850a2.zip

Marked as answer
Loader.
Up arrow icon