Invoke Parent Component Event from Child Component in Blazor – C#

To invoke a parent event in a child component button, click on Blazor Web Server; you can use EventCallback1.

Please find below a simple example.

 

ParentComponent.razor:

@page "/parent"

<div>@_message</div>

<ChildComponent OnClickCallParentEvent="ChildClickHandler" />

@code {

    private string _message;

 

    private void ChildClickHandler(string message)

    {

        _message = $"Child Clicked: {message}";

    }

}

Render ParentComponent in Index. razor, as shown below.

 

Index.razor:

@page "/"

<ParentComponent />

Please find below the code to invoke the parent component event from the Child Component.

 

ChildComponent.razor:

<button @onclick="ChildClick">Child Button</button>

@code {

    [Parameter]

    public EventCallback<string> OnClickCallParentEvent { get; set; }

 

    private void ChildClick()

    {

        OnClickCallParentEvent.InvokeAsync("Message from Child");

    }

}

The parent component contains a button that triggers the ParentClick method and a ChildComponent with an OnClick parameter.

 

The ChildComponent contains a button that, when clicked, invokes the OnClickCallParentEvent event callback with a message.

 

When you click the button in the child component, it calls the ChildClick method, which invokes the OnClickCallParentEvent callback event with the specified message. The parent component's ChildClickHandler method then handles this event.

                                                                                                                                                                                          Download Source Code