Share Data Between Child And Parent Components In Blazor

In this post, we will see how to create a reusable child component in Blazor and easily consume in another parent component. We will share the data between parent and child components and vice versa too.

Introduction


Blazor is a new framework built by Microsoft for creating interactive client-side web UI with .NET codebase. We can write both client-side and server-side code in C#.NET itself. I have already written five articles about Blazor server on C# Corner. Please refer to below articles for more basics about Blazor framework.
Components are implemented in Razor component files (. razor) using a combination of C# and HTML mark-up. A component in Blazor is formally referred to as a Razor component.
 
We can create a child component and reuse in another component. We will share data between these components very easily. We will create a custom textbox as child component. This custom textbox will show the current character count in the textbox and will restrict the total number of characters, if needed. I will explain all the actions step by step.

Create Blazor application in Visual Studio 2019


Choose Blazor template from Visual Studio 2019 and create Blazor application.
We can create a new razor component inside “Pages” folder.
 
 
We can define the html mark-up in the component.
  1. <div class="float-right">  
  2.     <i>Total Characters : @TextLength/@LengthString</i>  
  3. </div>  
  4.   
  5.    <div class="form-group row mb-2">  
  6.         <label class="col-md-3 col-form-label"  
  7.            for="Name">@FieldName</label>  
  8.         <div class="col-md7">  
  9.             <input class="form-control"  
  10.                    type="text"  
  11.                    placeholder="@FieldName" value="@Value" @oninput="OnValueChanged" maxlength="@MaxLength" />  
  12.         </div>  
  13.     </div>  
We can add the C# code also inside the @code block.
  1. @code {  
  2.        [Parameter]  
  3.        public string Value { getset; }  
  4.   
  5.        [Parameter]  
  6.        public string FieldName { getset; }  
  7.   
  8.        [Parameter]  
  9.        public int MaxLength { getset; } = -1;  
  10.   
  11.        [Parameter]  
  12.        public EventCallback<string> ValueChanged { getset; }  
  13.   
  14.        string LengthString;  
  15.        int TextLength;  
  16.   
  17.        protected override void OnInitialized()  
  18.        {  
  19.            TextLength = Value.Length;  
  20.            LengthString = (MaxLength == -1) ? "Unlimited" : MaxLength.ToString();  
  21.        }  
  22.   
  23.        private Task OnValueChanged(ChangeEventArgs e)  
  24.        {  
  25.            Value = e.Value.ToString();  
  26.            TextLength = Value.Length;  
  27.            return ValueChanged.InvokeAsync(Value);  
  28.        }  
  29.    }  
We have defined three parameters properties “Value”, “FieldName” and “MaxLength”.
 
FieldName is used for displaying field name and placeholder value in the custom textbox. MaxLength is used to restrict maximum characters limit in custom textbox, if needed. FieldName and MaxLength properties in Blazor act as @Input decorator in Angular. These properties are used to share data from parent component to child component. Value property acts as @Output decorator in Angular. This will be used for sharing data back from child component to parent component. In Angular, we use EventEmitter along with Output decorators to share data from child to parent component. In Blazor, we use “EventCallback” parameter to emit value from child component to parent component. Please note, “Changed” suffix is added to the value property parameter. This is the default convention used in Blazor.
 
We have created a “OnValueChanged” method and bind with “@oninput” attribute of input control in html mark-up.
 
CustomTextbox.razor
  1. <div class="float-right">  
  2.     <i>Total Characters : @TextLength/@LengthString</i>  
  3. </div>  
  4.   
  5.     <div class="form-group row mb-2">  
  6.         <label class="col-md-3 col-form-label"  
  7.            for="Name">@FieldName</label>  
  8.         <div class="col-md7">  
  9.             <input class="form-control"  
  10.                    type="text"  
  11.                    placeholder="@FieldName" value="@Value" @oninput="OnValueChanged" maxlength="@MaxLength" />  
  12.         </div>  
  13.     </div>  
  14.   
  15.     @code {  
  16.         [Parameter]  
  17.         public string Value { getset; }  
  18.   
  19.         [Parameter]  
  20.         public string FieldName { getset; }  
  21.   
  22.         [Parameter]  
  23.         public int MaxLength { getset; } = -1;  
  24.   
  25.         [Parameter]  
  26.         public EventCallback<string> ValueChanged { getset; }  
  27.   
  28.         string LengthString;  
  29.         int TextLength;  
  30.   
  31.         protected override void OnInitialized()  
  32.         {  
  33.             TextLength = Value.Length;  
  34.             LengthString = (MaxLength == -1) ? "Unlimited" : MaxLength.ToString();  
  35.         }  
  36.   
  37.         private Task OnValueChanged(ChangeEventArgs e)  
  38.         {  
  39.             Value = e.Value.ToString();  
  40.             TextLength = Value.Length;  
  41.             return ValueChanged.InvokeAsync(Value);  
  42.         }  
  43.     }  
We can add this child component inside a parent component. We can create new parent component.
 
ParentComponent.razor
  1. @page "/parentcomponent"  
  2.   
  3. <CustomTextbox @bind-Value="name" FieldName="Name" MaxLength="20" />  
  4. <CustomTextbox @bind-Value="address" FieldName="Address" />  
  5.   
  6. @code {  
  7.     string name = "Sarath Lal";  
  8.     string address = "Kakkanad";  
  9. }  
We have added two custom textbox child components inside this parent component. “@bind-{parametername}” is used for binding child component field with parent component field. Here, “Value” is the field name in the child component. So that, we used this as “@bind-Value”. We can pass these two input parameters “FieldName” and “MaxLength” from parent component. I have not passed MaxLength property for second child component. Hence, the default value -1 will be assigned to this component in run time.
 
We can modify the shared component “NavMenu” to add a navigation to parent component.
 
NavMenu.razor
  1. <div class="top-row pl-4 navbar navbar-dark">  
  2.     <a class="navbar-brand" href="">BlazorReusableComponent</a>  
  3.     <button class="navbar-toggler" @onclick="ToggleNavMenu">  
  4.         <span class="navbar-toggler-icon"></span>  
  5.     </button>  
  6. </div>  
  7.   
  8. <div class="@NavMenuCssClass" @onclick="ToggleNavMenu">  
  9.     <ul class="nav flex-column">  
  10.         <li class="nav-item px-3">  
  11.             <NavLink class="nav-link" href="" Match="NavLinkMatch.All">  
  12.                 <span class="oi oi-home" aria-hidden="true"></span> Home  
  13.             </NavLink>  
  14.         </li>  
  15.         <li class="nav-item px-3">  
  16.             <NavLink class="nav-link" href="counter">  
  17.                 <span class="oi oi-plus" aria-hidden="true"></span> Counter  
  18.             </NavLink>  
  19.         </li>  
  20.         <li class="nav-item px-3">  
  21.             <NavLink class="nav-link" href="fetchdata">  
  22.                 <span class="oi oi-list-rich" aria-hidden="true"></span> Fetch data  
  23.             </NavLink>  
  24.         </li>  
  25.         <li class="nav-item px-3">  
  26.             <NavLink class="nav-link" href="parentcomponent">  
  27.                 <span class="oi oi-list-rich" aria-hidden="true"></span> Parent Component  
  28.             </NavLink>  
  29.         </li>  
  30.     </ul>  
  31. </div>  
  32.   
  33. @code {  
  34.     bool collapseNavMenu = true;  
  35.   
  36.     string NavMenuCssClass => collapseNavMenu ? "collapse" : null;  
  37.   
  38.     void ToggleNavMenu()  
  39.     {  
  40.         collapseNavMenu = !collapseNavMenu;  
  41.     }  
  42. }  
We can run the application.
 
 
You can notice that, a new “Parent Component” link is appeared in the menu. You can click that link to see the parent component.
 
 
We have defined two custom textbox components inside the parent component. For the first textbox, we have given 20-character limit and for second component, no character limit is given. So that, you can enter unlimited characters in second textbox. The total characters count is also visible in the screen.

Conclusion


In this post, we have created a reusable child component in Blazor and easily used in another parent component. We have shared the data from parent component to child component and vice versa also.