Home > Enterprise >  How to pass data from child component to parent
How to pass data from child component to parent

Time:07-08

I can't seem to find any answer for this question but it seems simple enough to exist. Basically I want to send data from Child component to Parent.

Here is an example of Child component Cars

@using Newtonsoft.Json

@if(ReponseCarsJSON) {
  @foreach (var car in ReponseCarsJSON) {
    <p @onclick="() => onSelectCar(car.id)"> model: @car.model year: @car.registration_year </p>
    }
}


@code{
  [Parameter]
  public EventCallback<string> CarSelected { get; set; }

  async Task onSelectCar(string e) {
    await CarSelected.InvokeAsync(e);
  } 

  //ReponseCarsJSON = ... json stuff to fetch Cars API
}

My question is how do I retrieve this data on parent, for example:

<Cars CarSelected="@getCarId"> </Cars>

@code {
  private void getCarId () {
    // get car id here
  }
}

CodePudding user response:

Simply pass it as a parameter to your getCarId method. i.e.:

@code {
    private void getCarId(string carId) {
        // use carId here
    }
}

One thing I like to do to avoid any potential errors is to make sure there's actually a callback delegate registered. So I do:

private async Task onSelectCar(string e) {
    if (CarSelected.HasDelegate) {
        await CarSelected.InvokeAsync(e);
    }
}
  • Related