How to pass multiple arguments from child to parent upon onClick event in child component
Child Razor
@foreach( var item in items)
{
@foreach( var score in item.scores)
{
<span @onclick="ItemClicked(item.name, score.id)">
@item.name
</span>
}
}
Parent Razor
<Child ItemClicked = "@ItemClicked"/>
@code{
private void ItemClicked(string name, int id)
{
Console.WriteLine(name);
Console.WriteLine(id);
}
}
In Child
<span @onclick = "() => ItemClicked(item.name, score.id)"> @item.name</span>
@code
{
[Parameter] public Action<string,int> ItemClicked { get; set; }
}
What you can do is create a new class for the arguments you're trying to pass back up to the parent. In this example, I'm using a generic checkbox component that I pass an Id and a Checked property because I need to know what item I'm selecting in the parent component as well as if it's checked or not. So the event needs to know the Id and whether it's checked. The child component contains it's own logic and then passes up a new object with the assigned values which the parent can now use.
Parent
<Checkbox Id="@Id" Checked="@Item.Checked" CheckChanged="OnCheck" />
public class OnCheckEventArgs
{
public bool IsChecked {get; set;}
public long ItemId {get; set;}
}
public class ItemsOverview : ComponentBase
{
public void OnCheck(OnCheckEventArgs args)
{
// do stuff
}
}
Child
<input type="checkbox" Id="@Id" checked="@Checked" @onchange="CheckboxChanged" />
public partial class Checkbox : ComponentBase
{
[Parameter]
public long Id {get; set;}
[Parameter]
public bool Checked {get; set;}
[Parameter]
public EventCallback<OnCheckEventArgs> CheckChanged {get; set;}
protected async Task OnCheckChange(bool checked)
{
// do stuff
await CheckChanged.InvokeAsync(new OnCheckEventArgs { IsChecked = checked, ItemId = @Id });
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With