Calling public methods on Blazor component from another component

 
 
  • Gérald Barré

Blazor components are classes like any other .NET class, which means you can add public methods and call them from other components. For instance, if you create a dialog component, you can add Show or ShowModal methods and call them from a parent component to display the dialog as needed. Another example is adding Reset and Submit methods to a form.

Let's consider the following component (this is just a sample without the actual logic):

Razor
@* TODO actual html *@
<dialog></dialog>

@code {
    public void Show()
    {
        // TODO actual implementation
    }

    public void ShowModal()
    {
        // TODO actual implementation
    }
}

In Blazor, you can get an instance of a component by creating a component reference. To capture a component reference:

  • Add an @ref attribute to the child component
  • Define a field with the same type as the child component
Razor
<button @onclick="OnOpenButtonClick">Open</button>
<button @onclick="OnOpenModalButtonClick">Open modal</button>

@* 👇 Add a @ref to the component *@
<MyDialog @ref="myDialog1"></MyDialog>

@code {
    // 👇 Hold the reference to the component
    private MyDialog myDialog1;

    // 👇 Call the public methods of the component
    private void OnOpenButtonClick() => myDialog1.Show();
    private void OnOpenModalButtonClick() => myDialog1.ShowModal();
}

Note that the myDialog1 variable is only populated after the component is rendered. Until that point, there is nothing to reference. To manipulate component references after rendering is complete, use the OnAfterRenderAsync or OnAfterRender methods.

Prefer parameters over methods when possible. Parameters define the component's state and ensure it renders as expected. If you mutate component state through methods, a subsequent re-render may discard those changes. Use component references only when it truly makes sense.

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?