Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass data from child component to parent

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

>Solution :

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);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading