When a component needs data from outside to process, Parameter is a good technique for passing data from a parent component to its children. In this tutorial, you will discover:
Parameter
.You can download the example code used in this topic on GitHub.
Parameter
The following steps will help you to pass a parameter from the parent component to the child components.
EditorRequired
attribute. You can also set the default value of the parameter after getter and setter.@code { [Parameter] public string InputParameter { get; set; } = "Default Value"; [EditorRequired] [Parameter] public string RequiredInputParameter { get; set; } = ""; }
@code { public string FirstData { get; set; } = "First data"; public string SecondData { get; set; } = "Second data"; }
<Child InputParameter="FirstData" RequiredInputParameter="SecondData" />
For the parameter with the EditorRequired
attribute, you will need to pass it, or else you won't be able to build the project.
When using the Parameter technique, don't change the reference of a passed parameter in any child component. The following code in the child component illustrates this mistake:
@code { [Parameter] public ExampleClass ExampleInstance { get; set; } = new(); public void Correct() { ExampleInstance.Data = "Value changed"; } public void Mistake() { ExampleInstance = new() { Data = "Reference changed" }; } }
The changed value only affects in the child component and not in the parent component, as the following video illustrates:
You can change the value of a parameter in the parent component and in any of your child components. In this section, you will learn:
Anytime the parent component changes the value of a passed parameter, the child components will be re-rendered. You don't need to detect the changes from the parent component most of the time. In case you want to detect those changes, you can override the OnParametersSet()
method of your child component. See Component Lifecycle tutorial.
Unlike the changes coming from the parent component, anytime a child component updates a value of a passed parameter, the parent component will not be re-rendered. To make the parent component reacts to the changes, you need to pass a delegate to the child component as well. Whenever the child component update the parameter value, the child component will call the delegate to notify the parent component to update itself.
@code { [Parameter] public ExampleClass ExampleInstance { get; set; } = new(); [Parameter] public EventCallback ExampleInstanceChanged { get; set; } }
@code { ... public void UpdateValue() { ExampleInstance.Data = "Value changed at child"; ExampleInstanceChanged.InvokeAsync(); } }
StateHasChanged
along with the parameter to the child component.<Child ExampleInstance="ExampleInstance" ExampleInstanceChanged="StateHasChanged" />