Piotr Dabalaga
Piotr Dabalaga

Reputation: 41

Blazor - event callback from descendant

I've created test blazor server app with structure like this:

    <parent_component>
      <child1_component/>
    </parent_component>

Where:

    <child1_component>
      <child2_component/>
    </child1_component>

And

    <child2_component>
      <child3_component/>
    </child2_component>

How to receive event callback in parent_component sended by child3_component? Does structure of nested components make sense? Is it useful in 'real scenario' or should I use other structure?

Upvotes: 3

Views: 1396

Answers (2)

kite
kite

Reputation: 1548

I was also looking for this; My use case: I want to have centralized confirmationDialog components in my main layout, where I can call where ever a components need, so can be anywhere in the hierarchy.

Telerik has a predefined dialogs, but to bad its not working well when called from another dialog (grid edit popup), so need to use their TelerikWindow component.

This is sample from Telerik Blazor for In-memory state container service; basically put 1 component in the root for ConfirmationDialog, then using dependency injection in the component that want to use the ConfirmationDialog through the injected service. https://github.com/telerik/blazor-ui/tree/master/common/message-box

Upvotes: 1

Neil W
Neil W

Reputation: 9112

An EventCallback can be handled by the component that hosts the component declaring the EventCallback.

In other words, in your structure child3's event can be caught by child2.

To get the event to the parent, you have two options:

  1. Chain events through the stack so that Parent component eventually received EventCallback from child 1.

  2. Use a event broadcast service. Basically a service that registered at startup and can be injected into any component. Child3 will call a "Send" method to send the event to those listening. The event broadcast service will raise the event. ParentComponent will need to register with broadcast service that it can listen for events appropriate events.

Here's a good starter article about your situation:

https://chrissainty.com/3-ways-to-communicate-between-components-in-blazor/

Upvotes: 3

Related Questions