Blazor WASM Communication Between Components
Blazor
31 Articles
In this article, let's learn about how to communicate between components in Blazor WASM application.
Note: If you have not done so already, I recommend you read the article on Blazor WASM Event Handling And Event Arguments.
Table of Contents
Component Parameters
The simple and straight forward way is by passing values as Component Parameters. Component parameters pass data to components and are defined using public C# properties on the component class with the [Parameter] attribute.
Code Sample - Component Parameters Demo
Cascading Values and Parameters
Cascading values and parameters provide a convenient way to flow data down a component hierarchy from an ancestor component or parent component to any number of descendent components or child components. Unlike Component parameters, cascading values and parameters don't require an attribute assignment for each descendent component or child component where the data is consumed. Cascading values and parameters also allow components to coordinate with each other across a component hierarchy.
Code Sample - Cascading Values and Parameters Demo
Event Callbacks
EventCallback and EventCallback<T> are used to pass data from child component to parent component upon a certain event like button click. We can also assign synchronous or asynchronous methods and communicate to parent component using event callbacks along with data.
Code Sample - Event Callbacks Demo
State Container
This last method is the complex way to communicate between many components across the whole application. We need to register this state container as Scoped or Singleton service and inject the same and use it to store and pass data between components on any event.
Code Sample - State Container Demo
Summary
In this article, we learn't how to Communicate between components in blazor WASM application using 4 different techniques. We started with simple straight forward Component Parameters and Cascading Parameters and then moved to EventCallback and finally to State Container. I would recommend to make use of simple straight forward ways unless you need a complex state container.