Search code examples
c#eventemitterblazor

Responding to child-emitted events from parent component


I am having 2 components A and B , B being a child of A.Is there anything like the EventEmitter (Angular) in Blazor ? How can i attach an event handler in the parent that can respond to the output of its child ?

Child

<button onclick="Emit">Press me</button>
@functions(){
[Parameter] // i do not know how the `Output` is called
private string Pressed {get;set;}
public void Emit()
{
  //somehow emit `Pressed` to the parent , make him respond
}
}

Parent component

<Child [Pressed]="doSomething"> </Child>
@functions{
 doSomething(string value){
  Console.WriteLine("Child sent me : "+value);
 }
}

P.S Sorry for syntax errors ,i am quite new to blazor.


Solution

  • You can use an Action parameter

    <button onclick="Emit">Press me</button>
    @functions(){
    [Parameter] protected Action<string> Pressed {get;set;}
    
    public void Emit()
    {
      Pressed?.Invoke("Some String");
    }
    }
    

    In Emit, you use a conditional to check if anyone is subscribed to the Action and Invoke it, passing in the parameters.

    Don't forget, in the Parent, if you want the page to update, call StateHasChanged() in the "doSomething" method.