Hands-on: Task List Management Using EventCallback and Parameters
🔧 Tutorial: Task List Management Using EventCallback and Parameters
Building on our previous exercise about parent-child communication, this hands-on demo will guide you through creating a simple task management application in Blazor. This example vividly illustrates how you can combine parameters (data flowing down) and EventCallback (events flowing up) to create interactive and dynamic UIs where child components can influence the state of their parents.
1️⃣ Create the Child Component: TaskItem.razor
This component will represent a single task item. It will display the task's name and its completion status, and provide a button to mark the task as completed. When the button is clicked, it will notify its parent.
Create a new Razor component file named TaskItem.razor in your Components or Shared folder.
<!-- Components/TaskItem.razor -->
<div class="child-card-demo">
<h4>@TaskName</h4>
<p>Status: <b>@(IsCompleted ? "✅ Completed" : "❌ Pending")</b></p>
<button @onclick="MarkCompleted" disabled="@IsCompleted">Mark as Completed</button>
</div>
@code {
// Parameter to receive the task name from the parent
[Parameter] public string TaskName { get; set; }
// Parameter to receive the completion status from the parent
[Parameter] public bool IsCompleted { get; set; }
// EventCallback to notify the parent when the task is completed
// It will pass the TaskName back to the parent.
[Parameter] public EventCallback<string> OnCompleted { get; set; }
// Method to handle the button click
private async Task MarkCompleted()
{
// Only invoke the event if the task is not already completed
if (!IsCompleted)
{
// Invoke the EventCallback, passing the TaskName as an argument
await OnCompleted.InvokeAsync(TaskName);
}
}
}
2️⃣ Create the Parent Page: TaskManager.razor
This page will manage a list of tasks and render multiple TaskItem components using a loop. It will also handle the completion event raised by each child task.
Create a new Razor page file named TaskManager.razor in your Pages folder.
<!-- Pages/TaskManager.razor -->
@page "/tasks"
<h2 class="heading2">📝 Task Manager</h2>
<!-- Loop through the list of tasks and render a TaskItem component for each -->
@foreach (var task in tasks)
{
<TaskItem
TaskName="@task.Name"
IsCompleted="@task.IsCompleted"
OnCompleted="HandleTaskCompletion" /> <!-- Assign the event handler -->
}
@if (!string.IsNullOrEmpty(lastUpdate))
{
<p class="parent-message"><b>Last Update:</b> @lastUpdate</p>
}
@code {
// Define a simple model for our tasks
public class TaskModel
{
public string Name { get; set; }
public bool IsCompleted { get; set; }
}
// Initialize a list of tasks
List<TaskModel> tasks = new()
{
new TaskModel { Name = "Prepare Slides", IsCompleted = false },
new TaskModel { Name = "Send Report", IsCompleted = false },
new TaskModel { Name = "Fix Bug #102", IsCompleted = false }
};
// Property to store the last update message from a child
string lastUpdate;
// Method to handle the OnCompleted event raised by TaskItem children
void HandleTaskCompletion(string taskName)
{
// Find the task in the list by its name
var task = tasks.FirstOrDefault(t => t.Name == taskName);
if (task != null)
{
task.IsCompleted = true; // Update the task's status
// Update the lastUpdate message
lastUpdate = $"Task '{taskName}' marked as completed at {DateTime.Now:T}";
// Blazor will automatically re-render the parent and affected children
// because the 'tasks' list (a state variable) has changed.
}
}
}
Note: Ensure that the namespace of your TaskItem.razor is imported into _Imports.razor or directly into TaskManager.razor using an @using directive, if not already. For example, if TaskItem is in `YourApp.Components`, add `@using YourApp.Components`.
🎯 Learning Highlights for Students:
- Component List Rendering: This demo effectively uses the
@foreachloop to dynamically render a list ofTaskItemchild components based on thetaskscollection in the parent. - Passing State Down: Each
TaskItemchild component receives its specific task information (TaskNameandIsCompleted) from the parent via[Parameter]properties. - Raising Events Up: When a user clicks "Mark as Completed" on a
TaskItem, the child component usesEventCallbackto notify itsTaskManagerparent that a specific task has been completed. - Updating Parent State: The parent's
HandleTaskCompletionmethod receives the event, identifies the completed task, and updates itstaskslist. Blazor's rendering engine then efficiently updates only the affectedTaskItemcomponent (and thelastUpdateparagraph) to reflect the new state.
This demo provides a comprehensive example of how to build interactive lists and manage state across components in Blazor, which is a common pattern in real-world applications.
Comments
Post a Comment