blazorblazor-server-sidefluent-ui

Blazor server - Fluent UI - Set focus to a FluentDatePicker


I can set focus to a FluentTextField:

If I try to do the same with a FluentDatePicker, I get this error in the console:

ElementReference has not been configured correctly.

So, the question is: how to set focus from code to a FluentDatePicker?

Many thanks and bye ...


Solution

  • If I try to do the same with a FluentDatePicker, I get this error in the console:

    ElementReference has not been configured correctly.

    It seems that this is a known issue, we can't reference the FluentDataPicker like the FluentTextField at present.

    So, the question is: how to set focus from code to a FluentDatePicker?

    You could refer to the following sample to set focus using the JavaScript method:

    1. Add the JavaScript script in App.razor page:

       <script>
           function focusFluentDatePicker(elementId) {
               const datePicker = document.getElementById(elementId);
               if (datePicker) {
                   datePicker.focus(); //set focus.
                   datePicker.click(); //show the date picker calendar.
               }
           }
       </script>
      
    2. In the Main component, use a FluentButton @onclick event to set focus:

       @page "/fluentui"
       @rendermode InteractiveServer   
       @inject IJSRuntime JSRuntime
       <h3>FluentUI</h3> 
       <div style="display:flex">
           <FluentButton @onclick="() => focusTest!.FocusAsync()">FocusAsync</FluentButton>
           <FluentTextField @ref="focusTest" @bind-Value=value></FluentTextField>
       </div>
       <div style="display:flex"> 
           <FluentButton @onclick="SetFocus" >Focus Date Picker Async</FluentButton>
           <FluentDatePicker @ref="datePicker" @bind-Value="@SelectedValue" 
               id="myDatePicker" />
       </div>
           <p>
               Selected Date: @(SelectedValue?.ToString("yyyy-MM-dd"))
           </p>
       @code
       {
           FluentTextField? focusTest; 
           FluentDatePicker? datePicker;
           string? value;
           private DateTime? SelectedValue = DateTime.Today.AddDays(-2); //default date 
           private async void SetFocus()
           {
               var id = this.datePicker.Id; //get the DataPicker id attribute.
               await JSRuntime.InvokeVoidAsync("focusFluentDatePicker", id);
           }
       }
      

    After running the application and then click the FocusDataPickerAsync button, the result as below: it will focus the datepicker and open the calendar, if you don't want to open the calendar, remove the datePicker.click();.

    test result