Blazor cascading values and parameters

One way to pass data from Parent component to child component is by using component parameters. We discussed component parameters in detail in Part 27 of Blazor tutorial.

Cascading values and parameters

blazor cascading values and parameters

A blazor application is a set of components. We create individual components and put them together to create a working blazor application. Components can also be nested. A component can be nested in another component. That component can be nested in yet another component and this can go on.

However, when there are several component layers in the component hierarchy, it's tedious to pass data from an ancestor component to a descendent component using component parameters. This is when we use cascading values and parameters. They provide a convenient way for an ancestor component to pass a value to all of its descendent components.

Blazor CascadingValue Component

Blazor has a built-in component called CascadingValue. We can pass a value to this component. This value is then cascaded down its component tree to all of its descendants. 

blazor cascading parameters example

In the following example, ParentComponent Style property value is passed to the CascadingValue component.


@page "/pc"

<h1 style="@Color">Parent Component Text</h1>

<CascadingValue Value="@Style">

@code {
    public string Style { get; set; } = "color:red";

Accessing Cascading Value

The child component can access the cascading value by declaring a property of the same type, decorated with the [CascadingParameter] attribute. In fact, any of the descendant components in the component tree can access the cascading value. They simply have to declare a property of the same type, decorated with the [CascadingParameter] attribute.


<h1 style="@ElementStyle">-Child Component</h1>


@code {
    public string ElementStyle { get; set; }

Along the samelines, even the GrandChildComponent can access the Cascading Value


<h1 style="@ElementStyle">--Grand Child Component Text</h1>

@code {
    public string ElementStyle { get; set; }

Next : Multiple Cascading Parameters

© 2020 Pragimtech. All Rights Reserved.