In this lesson, you will learn how to create a bidirectional data flow between parent and child components in Blazor using parameters and EventCallback.
Passing Data Down (Parameters)
In Blazor, components are hierarchical. A parent component can pass information to a child component by defining properties in the child decorated with the [Parameter] attribute. Think of this like passing an argument into a method; the parent "calls" the child and hands it the data it needs to render.
ChildComponent.razor:
<h3>@Title</h3>
@code {
[Parameter] public string Title { get; set; }
}
ParentComponent.razor:
<ChildComponent Title="Hello from Parent!" />
Passing Data Up (EventCallbacks)
While data flows down easily through parameters, child components often need to notify their parents when something happens (like a button click). We use an EventCallback for this. The parent assigns a method to the child's callback property, and the child "invokes" that callback when it's time to communicate back.
ChildComponent.razor:
<button @onclick="NotifyParent">Click Me</button>
@code {
[Parameter] public EventCallback<string> OnStatusChange { get; set; }
private async Task NotifyParent()
{
await OnStatusChange.InvokeAsync("Child button was clicked!");
}
}
ParentComponent.razor:
<ChildComponent OnStatusChange="HandleChildNotification" />
@code {
private void HandleChildNotification(string message)
{
Console.WriteLine(message);
}
}
Why this matters
By using [Parameter] for inputs and EventCallback for outputs, you keep your components decoupled. The child doesn't need to know who the parent is or what the parent does with the information; it simply broadcasts that an event occurred. This pattern ensures your UI remains predictable and easier to debug, as data flows in a clear, single direction.
Key Takeaway: Use [Parameter] to inject data into child components, and EventCallback to bubble signals or data back up to the parent.