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);
}
}
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
MainPage.razor
Click "Get Child" you will see "old value"; After click "Child changeValue" and then click "Get Child" again you will see "new value".