Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor - passing arguments to parent

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);
    }
}
like image 306
Ahmed Imam Avatar asked May 24 '20 17:05

Ahmed Imam


2 Answers

In Child

<span @onclick = "() => ItemClicked(item.name, score.id)"> @item.name</span>

@code 
{
   [Parameter] public Action<string,int> ItemClicked { get; set; }
}
like image 192
Henk Holterman Avatar answered Nov 02 '22 21:11

Henk Holterman


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 });
    }
}
like image 3
visualbam Avatar answered Nov 02 '22 22:11

visualbam