Today i was working on one blazor POC project, there i got a requirement to pass some value to all the child components which one i was using on the parent component.
Then i found one of the best approach to pass in all the child component using Cascading Values & Cascading Parameters
Let see this concept one small example.
Step 1: Create the parent component like this
@page "/home" <CascadingValue Value="@FirstFruit" IsFixed="true" Name="FirstFruit"> <Fruit></Fruit> </CascadingValue> @code { string FirstFruit { get; set; } = "Apple"; }
In the above code, i m passing FirstFruit property to all the child component, There could be multiple child component. For simplicity i have taken only one.
IsFixed=”true” means Blazor will not monitor it for changes. It is good practice to improve the performance when there will be multiple child component.
Step 2: Create the Fruit Component like this.
<h5>Demo for Cascading Value and Cascading Parameter</h5><br /> <p>The fruit Name is: @Name </p> @code { [CascadingParameter(Name = "FirstFruit")] string Name { get; set; } }
In the above code CascadingParameter means which field will receive the Cascading Value.
(Name = “FirstFruit”): Means which field we are going to bind from parent component.
Summary
In this sample we saw that how pass the value from parent component to multiple child component with a very minimal coding.