I want the create a Blazor component, in which a component (a.k.a a dialog box) is popped up to the user (the popped component will be embedded in the main component), and then after the user selects an item from the embed dialog component, the parent component will be notified, and will be able to retrieve the selection data from the embed component, just like a dialog box in desktop applications.
A pseudo code example of what I want:
<h1>main component</h1>
<EmbedComponent></EmbedComponent>
@code
{
private void OnSelection(Item selectedItem ){}
}
<h1>embed component</h1>
<h1>please choose:</h1>
<button @onclick="NotifyParent(item1)">option1<button>
<button @onclick="NotifyParent(item2)">option2<button>
How can I do that (in Blazor WebAssembly)?
You want to use an EventCallback.
Listen for the event in the parent:
<h1>main component</h1>
<EmbededComponent OnSelection="OnSelection" />
@code
{
private void OnSelection(Item selectedItem ){}
}
Receive the callback as a parameter and trigger from the child:
<h1>embeded component</h1>
<h1>please choose:</h1>
<button @onclick="() => NotifyParent(item1)">option1<button>
<button @onclick="() => NotifyParent(item2)">option2<button>
@code {
[Parameter]
public EventCallback<Item> OnSelection { get; set; }
public async Task NotifyParent(Item item) {
if (OnSelection.HasDelegate) {
await OnSelection.InvokeAsync(item);
}
}
}