Exercise 5: Parent–Child Communication with EventCallback and Parameters
Exercise 5: Parent–Child Communication with EventCallback and Parameters
You've mastered routing, reusable components, and data binding. Now, let’s explore one of the most important real-world concepts in Blazor: **event communication between components**. In complex applications, components often need to interact. This exercise will teach you how to pass data down from a parent to a child, and how a child can notify its parent of an event using EventCallback.
✅ Goal:
Build a parent-child relationship where:
- The parent sends data to the child via
[Parameter]. - The child raises an event back to the parent using
EventCallback.
🧩 Concepts Covered:
- Understanding and using the
[Parameter]attribute for parent-to-child data flow. - Understanding and using
[EventCallback]for child-to-parent event notification. - Promoting reusability through effective component isolation.
- Binding data and behavior across different components in a Blazor application.
🔧 Steps:
Step 1: Create a reusable component named ChildCard.razor
Create a new Razor component file named ChildCard.razor in your Shared or Components folder. This component will display a title and have a button that, when clicked, sends a message back to its parent.
<!-- Shared/ChildCard.razor -->
<div class="child-card-demo">
<h4>Card Title: @Title</h4>
<button @onclick="SendDataToParent">Notify Parent</button>
</div>
@code {
// [Parameter] to receive data from the parent
[Parameter] public string Title { get; set; }
// [Parameter] of type EventCallback to send events back to the parent
// The indicates that this EventCallback will pass a string argument.
[Parameter] public EventCallback<string> OnNotify { get; set; }
// Method called when the button is clicked
void SendDataToParent()
{
// Invoke the EventCallback, passing a message to the parent
OnNotify.InvokeAsync($"Card '{Title}' clicked at {DateTime.Now:T}");
}
}
Step 2: Use this component in a parent page, e.g., ParentComponent.razor
Create a new Razor page named ParentComponent.razor in your Pages folder. This page will render multiple instances of ChildCard and will include a method to handle the events raised by its children.
<!-- Pages/ParentComponent.razor -->
@page "/parent"
<h3 class="heading3">Parent Component</h3>
<!-- Render two instances of ChildCard, passing a Title and an event handler -->
<ChildCard Title="First Card" OnNotify="HandleNotification" />
<ChildCard Title="Second Card" OnNotify="HandleNotification" />
@if (!string.IsNullOrEmpty(lastMessage))
{
<p class="parent-message"><b>Message from child:</b> @lastMessage</p>
}
@code {
// Property to store the last message received from a child
string lastMessage;
// Method to handle the EventCallback from the ChildCard
void HandleNotification(string message)
{
lastMessage = message; // Update the parent's state
// StateHasChanged() is usually called automatically after event handlers,
// but can be called manually if updates are not reflected immediately.
}
}
Note: Ensure that the namespace of your ChildCard.razor is imported into _Imports.razor or directly into ParentComponent.razor using an @using directive, if not already. For example, if ChildCard is in `YourApp.Shared`, add `@using YourApp.Shared`.
Step 3: Run the app and visit /parent in the browser.
Execute your Blazor application and navigate to the /parent route.
🧪 Try this:
- Run the app and go to
/parent. - You should see "Parent Component" heading and two "Card Title" components below it, each with a "Notify Parent" button.
- Click both “Notify Parent” buttons from each card.
- Observe how the "Message from child:" text in the parent component updates each time you click a button, showing which card was clicked and when.
- Modify the
Titleparameter passed to theChildCardcomponents inParentComponent.razorand re-run to test reusability.
🎯 Expected Output:
You will see two distinct cards, each with its specified title. Clicking the "Notify Parent" button on either card will update a message displayed in the parent component, showing the title of the card that was clicked and the timestamp.
Card Title: First Card
Card Title: Second Card
(The message will change based on which button you click last).
This exercise clearly demonstrates the flow of data and events in Blazor: parameters for data flowing down, and EventCallback for events flowing up, enabling robust and maintainable component architectures.
🧠 Bonus Challenges:
- Pass a more complex object: Instead of just a
string, modifyOnNotifyto pass a custom C# object (e.g., aCardInfoclass with properties likeCardId,CardTitle,Timestamp) from the child to the parent. - Disable the child button: Add logic to the
ChildCardto disable its "Notify Parent" button after it has sent the event once. - Generate multiple
ChildCards: Create aList<string>of card titles in the parent, and then use a@foreachloop to dynamically render multipleChildCardcomponents based on this list.
Would you like to proceed with Exercise 6: Building a Form with Validation using EditForm, DataAnnotationsValidator, and custom input controls? This will bring together many of the concepts we've covered into a practical form scenario.
Comments
Post a Comment