How-To: Define EventCallback on Blazor Component

In some cases, a Blazor component needs to inform its parent of a state change. Blazor uses an EventCallback to define how events are passed from a component to its parent component or page. That parent’s method gets called whenever the child component’s event is fired. Defining an EventCallback is similar to how we place parameters on components.

There are two flavors: EventCallback and EventCallback<T>.

  • EventCallback specifies a target method with no parameters.
  • EventCallback<T> specifies a target method with a single parameter of type T.
  • We can also provide a synchronous or asynchronous method to an EventCallback without having to change the type.

To investigate EventCallbacks, we must have a Blazor component. Either open an existing Blazor project, or please follow the steps in the How-To: Create New Blazor Component article to get setup. For this article, we called the project: Blazor.HowTo and the component: BannerAd.

Define Component with EventCallback

We are going to extend the BannerAd component from the New Component article by adding some parameters and an EventCallback to it.

Let’s start by updating the BannerAd component in the Blazor.HowTo project and Components folder.

<div class="col-12 pt-1 rounded border"
     style="background-color: lightgray; cursor: pointer"
     @onclick="AdClicked">
    <img class="float-left mr-2 mt-2 align-items-center" src="@ImageLink" />
    <h5><strong>@Title</strong></h5>
    <p style="font-size: small">
        @ChildContent
    </p>
</div>

@code {
    [Parameter]
    public string Title { get; set; }

    [Parameter]
    public string ImageLink { get; set; }

    [Parameter]
    public RenderFragment ChildContent { get; set; }

    [Parameter]
    public EventCallback AdClicked { get; set; }
}

For the details on how parameters work, please read How-To: Define Parameters on a Blazor Component.

First, we define a public property called AdClicked with a getter and setter (line #22). The type of this property must be an EventCallback, because the click event doesn’t pass any parameters.

Then, we add the [Parameter] attribute on the property to surface it from our component and make it settable by the parent component/page (line #21).

Finally, we add an onclick event handler to the div container for this component, and we map the handler to the AdClicked EventCallback (line #3). The EventCallback will be invoked directly if we bind it this way.

Consume Component with EventCallback

With the EventCallback parameter exposed by our component, now we need to consume the component and set a method as the handler for that event. Let’s make the following changes to the Index.razor page in the Blazor.HowTo project and Pages folder.

@page "/"
@inject NavigationManager nav

<h1>Welcome to Blazor How-To!</h1>

<p>Welcome to your new app.</p>

<div class="col-lg-8 offset-lg-2 col-12 mt-5">
    <BannerAd ImageLink="/images/blazor-ad-image.png" AdClicked="@OnAdClicked"
              Title="My Blazor Ad!">
        Learn about the <strong>.NET 5</strong> technology for building single page applications <i>(SPAs)</i>.
        Transfer your knowledge of C# and .NET into the exciting realm of frontend development.
    </BannerAd>
</div>

@code {
    private void OnAdClicked()
    {
        nav.NavigateTo("https://docs.microsoft.com/en-us/aspnet/core/blazor/?view=aspnetcore-5.0");
    }
}

First, we require the Blazor NavigationManager service in this page, so we @inject it into the page (line #2).

Then, we define the OnAdClicked event handler method in our @code block. This method just uses the NavigationManager to navigate to a hard-code URL (lines #17-20).

Finally, we set the component’s AdClicked EventCallback to the OnAdClicked method (line #9). This way whenever the AdClicked EventCallback is invoked in our component, the page method will be called.

With this code in place, we can build and run (Ctrl + F5) our project to test the EventCallback. And if we click on the home page ad, we show that the event is hooked up correctly by navigating to a different page.

Fig 1 – Blazor Component with EventCallback

In conclusion, we showed how to add an EventCallback to a component and then how to use it from a parent component or page. EventCallback is a power mechanism for allowing communication back out of our component in response to a user action. We can see that many built-in Blazor components expose EventCallbacks, and we will need them in our custom components too.

One thought on “How-To: Define EventCallback on Blazor Component

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s