Calling public methods on Blazor component from another component

 
 
  • Gérald Barré

Blazor components are classes like any other .NET class. This means you can add public methods and call them from the parent components. For instance, if you create a dialog component, you can add a method ShowDialog or ShowModalDialog. In the parent component, you can call these methods to show the dialog the way you want. Another example is to add 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 and its output includes the element. Until that point, there's nothing to reference. To manipulate components references after the component has finished rendering, use the OnAfterRenderAsync or OnAfterRender methods.

Last but not least, you should use parameters when possible. Parameters allow us to define the state of the component, so it renders the component as expected. If you start mutating the state of the component using methods, a re-rendering of the component may discard some changes applied using methods. So, keep using references only when it makes sense.

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

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub