How to communicate Child component to parent component in Blazor ?


If you are giving interview on Blazor, you will face this question. We can communicate child component to parent component using EventCallback.

We will create one Child Component with Textbox as Input and Button. Whenever user will pass the input on textbox and click on Button. Then input text will display on Parent Component.

Child Component code snippet

<div>
    <input type="text" @bind="@message" />
    <button @onclick="DisplayMessage">Click Here</button>
</div>

@code {

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

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


Parent Component code snippet

@page "/"

<PageTitle>Index</PageTitle>

<SurveyPrompt InputParam="message" OnClickCallback="@ShowMessage" />
<p>@message</p>

@code
{
    private string message;

    private void ShowMessage(string _message)
    {
        message = _message;
    }
}

Summary: In the above demo, we saw that using EventCallback, we can communicate from child component to parent component.

If you are looking how to trigger Parent to Child component, then please read this post

How to refresh Parent to Child Component in Blazor ?

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.