Communicating from Parent to Child in Blazor

41 Views Asked by At

Consider a parent MainPage.razor and child components NewItemComponent.razor and Save.razor. Now when I click a button in Save.razor, I am communicating to Parent MainPage.razor through EventCallback.

Now I would like to communicate from the MainPage.razor (Parent) with the another child NewItemComponent.razor to retrieve the user entered name. How to do this?

Once I am able to access the NewItemComponent.razor then I can send the CurrentValue using EventCallBack (Because there will be few input properties and so I thought I can use EventCallback and send the information back to MainPage.razor).

But I am stuck in how to communicate from the MainPage.razor to NewItemComponent.razor.

MainPage.razor

<NewItemComponent ></NewItemComponent> 
<Save OnSaveClick="HandleSaveClick"></Save>

@code {
    
    private void HandleSaveClick()
    {
      //Gets executed when Save button is clicked
    }
}

NewItemComponent.razor

Enter Item Name <input type="text" class="form-control textbox-parameters" @bind="CurrentValue" >

@code { 
private string CurrentValue { get; set; } = "New Item"; 
}

Save.razor

<button class="btn btn-primary" @onclick="SaveClicked">Save</button>

@code {

    [Parameter]
    public EventCallback<bool> OnSaveClick { get; set; }

    private async void SaveClicked()
    {
        await OnSaveClick.InvokeAsync(true);
    }
}
1

There are 1 best solutions below

0
Qiang Fu On

You just need to create a "child1" instance by using ChildComponent child1; inside MainPage.razor. Then make sure any ChildCompoent you are using is referencing this instance by <ChildComponent @ref="child1" />. You could try following:
ChildComponent.rzor

//The value could be changed by click
<button @onclick="@(()=>{ChildInfo="new value";})">Child changeValue</button>
@code {
    public string ChildInfo { get; set; } = "old value";

}

MainPage.razor

@page "/"
<button @onclick="GetInfo">Get Child</button>
<ChildComponent @ref="child1" />    @* Any ChildCompnent you are using reference to "child1" *@

@Information

@code {
    private string Information;

    ChildComponent child1;  // Create a specified instance named "child1"
    private void GetInfo()
    {     
        Information = child1.ChildInfo;
    }
}

Click "Get Child" you will see "old value"; After click "Child changeValue" and then click "Get Child" again you will see "new value".