Search code examples
blazormudblazor

How do I setFocus to a MudTextField that is embedded in a Child Component?


I have a .razor page (Parent) that contains a child Component which is a MudTextField. When the user navigates to the Parent Page I want the Focus / Cursor to be in the MudTextField. How do I get the reference of the MudTextField in the Child to the Parent?

Note: I noticed I spelled Parent incorrectly in my code. I corrected this after taking the screenshots.

Thank you

Child Component within the Parent

Child

EventCallBack in the Parent

CallBack

MudTextField in the Child Component

MudTextField

Child Function to Parent

Child Function


Solution

  • In your component add a FocusTextField method

        public async Task FocusTextField()
        {
            await refUserInputField.FocusAsync();
        }
    

    Then when instantiating your component use a ref to it like

    <TestComponent @ref="testComponentRef" />
    @code {
      private TestComponent testComponentRef;
    }
    

    Then to trigger it just await testComponentRef.FocusTextField()