Vitaly
Vitaly

Reputation: 431

Child subscribing to parent's events

It is trivial in Blazor to subscribe a parent control to child's events: in the child, I just declare

[Parameter] Func OnClick { get; set; }

and assign a parent's method to OnClick in the child control markup. However, how can I achieve the opposite? I want the child to react to events from the parent control. So far I am just plain calling child methods from the parent - is there a better approach?

Upvotes: 3

Views: 2849

Answers (1)

enet
enet

Reputation: 45764

You can define an event on the parent component which can be handled by subscribers (for instance, a child component) when the event is raised.

On parent component

Define an event handler, say, StateChanged

public event EventHandler StateChanged;

Raise the event from code on the parent

StateChanged?.Invoke(this, EventArgs.Empty); 

On the child component

// Subscribe to the event defined on the parent component
protected async override Task OnInitAsync()
        {
            ParentComponent.StateChanged += OnStateChanged;
}

// Dispose of the component
        void IDisposable.Dispose()
        {
            ParentComponent.StateChanged -= OnStateChanged;
        }

        void OnStateChanged(object sender, EventArgs e) => Call_A_Method_That_Do_Something();

Hope this helps...

Upvotes: 5

Related Questions