Cascading Values and Cascading Parameters in Blazor
This blog is going to explain what Cascading values and Cascading parameters are. And it is going to explain with examples how to use them. You can easily transfer values from parent to child components using cascading values and cascading parameters.
Let's look at a small example. There are two components: parent and child components. In the code below, a text box is included to get the value to send to child components. Added CascadingValue component with value attribute to send value. Inside the CascadingValue a child component was added to get the value.
Parent.razorBelow one is a child component code. Here the [CascadingParameter] attribute is added to the ReceivedValue property variable. If you notice this, the variable name (ValueToPass) of the parent component does not match the value of the child component (ReceivedValue). But the value will cascade down to the child by data type(int).
Child.razorThe following image is the output of the code above. The child component is highlighted with background blue. As the value of the parent component changes, it also changes in the child component.
Pass Multiple values
By Type
The next example is going to illustrate how to pass multiple values to the child component using CascadingValues and CascadingParameters. The following code is a Parent component code. Here you can see two CascadingValue components are added along with value attributes. The first value is movieName which is a string type. The second value is a releasedYear which is an int type.
Parent.razorThe following is a child component code. Here you can see two property variables are declared with [CascadingParameter]. The first one is ‘Name’ with string type and the second one is ‘Year’ with int type.
Child.razorOutput
The output of the code above is below. Here you can see how values are passed from parent to child by type.
By Name
'By name' is the best way to send multiple values. For this, you need to add the 'Name' attribute to the CascadingValue components. The 'Name' attribute helps the child component to receive the value. In the example below, you can see that the 'Name' attribute is assigned with the values "name" and "product".
Parent.razorThe following is a child component in which you can see the [CascadingParameter] attribute added with the Name property. The same names (name and product) of the parent components are assigned to the Name attributes.
Child.razorOutput
The below one is an output of the above code.
I hope this helps you. Keep coding.
Comments
Post a Comment