Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor - Execute a parent component's method when a child component onclick event occurs

I need that onclick event occurring in the child component, execute ShowMessage method in parent component passing message string as parameter. The following code is not working:

child.razor:

    <input type="text" @bind-value="@message" @onclick="OnClickCallback"/>

    <button @onclick="ChangePassword">Parent button</button>

@code {
    private string message;
    
    [Parameter]
    private string Message {get; set;}

    [Parameter]
    public EventCallback<MouseEventArgs> OnClickCallback {get; set;}

    [Parameter]
    public EventCallback<string> OnClick { get; set; }

    private async Task ChangePassword()
    {
        await OnClick.InvokeAsync(message);
    }
    
}

parent.razor:

@page "/parent"

<Child @bind-Message="message" OnClickCallback="@ShowMessage"></Child>

<p>@message</p>

@code {
    private string message;

    private void ShowMessage(MouseEventArgs args, string e)
    {
        message = e;
    }
}

Error: cannot convert from 'method group' to 'EventCallback' on OnClickCallback="@ShowMessage"

like image 586
Rodrigo Nascentes Avatar asked Mar 23 '26 08:03

Rodrigo Nascentes


1 Answers

You'll need to define two parameter properties, one to contain the message passed from the parent component, and the second, to hold the callback to the parent's ShowMessage method that will be called when you click on the "Parent button" button

Child.razor

 <input type="text" @bind="@message" />

    <button @onclick="ChangePassword">Parent button</button>

@code {
    private string message;
    
    [Parameter]
    public string Message {get; set;}
       
    [Parameter]
    public EventCallback<string> OnClickCallback {get; set;}

    
    private async Task ChangePassword()
    {
        await OnClickCallback.InvokeAsync(message);
    }
    

Parent.razor

 @page "/parent"
    
    <Child Message="message" OnClickCallback="@ShowMessage"/>
<p>@message</p>

@code {
    private string message;

   private void ShowMessage(string _message)
    {
        message = _message;
    }
}
like image 88
enet Avatar answered Mar 24 '26 22:03

enet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!