Reputation: 9360
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.
Upvotes: 3
Views: 918
Reputation: 45586
// Define a method in the parent component which will be called
// from the child component when the user tap the button residing
// in the child component. This method has a string parameter passed
// from the child component
public void GetValueFromChild(string value)
{
// Do somethig with value
}
Component B.cshtml
// When the user click the button the method GetValueFromChild
// defined on the parent component is called
<button class="btn" onclick=@(() => OnAddValue("some string value"))>Add</button>
@functions
{
// Define an Action delegate property which stores a reference
// to A.GetValueFromChild
// Parameters
[Parameter] Action<string> OnAddValue{ get; set; }
}
// Here (in the parent component) you place the child component and
// set its OnAddValue to the name of the method to be called
<B OnAddValue = "GetValueFromChild"></B>
Please mark my answer as accepted if it helped you out
Hope this helps...
Upvotes: 3
Reputation: 8954
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.
Upvotes: 5